Menu
Coddy logo textTech

Declaration & Initialization

Lesson 2 of 14 in Coddy's C++ Pointers course.

The syntax for pointer declaration consists of a variable type that the pointer will point to, the asterisk (*) symbol to let the compiler know it's a pointer, and a pointer variable name.

// varType *ptrName;
int *ptr;

We can declare any type of pointer, an int pointer, a string pointer, bool, float, or double, we can point to objects, to structures, etc.

int var = 5;
int *ptr = &var;
cout << "Address of var: " << ptr;
Output:
0x7fffffa84984

In this code, the pointer ptr of type int points to var, and in order to initialize its value so it points to something, we use the ampersand (&) operator to get the value of var

  • During declaration we use the asterisk (*) symbol to indicate we are creating a pointer to the specified variable type
  • If we want to get the address of a given variable we use the ampersand (&) symbol
  • The asterisk (*) symbol is also used for dereferencing. When you use * in conjunction with a pointer, it allows you to access the value stored at the memory address the pointer is pointing to
int var = 10;
int *ptr = &var;
cout << "Value stored on address " 
 << ptr << " is " << *ptr;
Output:
Value stored on address 0x7fff4ec0de14 is 10
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Perform the following tasks in your code

  • Declare a pointer of type bool called boolPtr
  • Declare an integer called num
  • Input an integer from standard input and store it in num
  • Declare an integer pointer called intPtr and initialize its value to be the address of num
  • Print out the value of intPtr using dereferencing

Try it yourself

#include <iostream>

using namespace std;

int main() {
    
    // Enter your code here
    
    return 0;
};

All lessons in C++ Pointers