A pointer is an object (variable) whose value is an address of another object (variable). Dereferencing a pointer yields the variable (lvalue) it is pointing. We can get the address of the variable using address-of operator. For example:

int value{100};
std::cout << &value; // address-of value
 
std::cout << *&value; // derefencing address-of value

As an aside

Any object created is stored in memory which is access using memory address. For example,

int x {1};

Let’s say variable x is stored at memory address x05F43C, whenever we use this variable, the program will access the value by looking at this memory address. However, we do not use memory addresses in the programs. Compiler does the magic of managing these addresses. We just use variables to access values.

Info

Modern C++ has introduced smart pointers which are different from pointers (raw pointers or dump pointers) that we are currently discussing.

Pointer initialization

Pointer has not be initialized as it has to be done with references. An uninitialized pointer is called wild pointer. Dereferencing these pointers result in undefined behaviors as they point to some garbage value.

A pointer can be initialized as shown below:

int value{100};
int* iptr{&value};

We assign address of value to int pointer iptr. The type of pointer should match the type of variable it would be pointing. For example, creating int pointer to float variable would not work.

double value{10.0};
int* iptr{&value}; // it will fail.

We can’t initialize pointer to a literal value as shown below:

int* iptr{5}; // it will fail.

Note

Prefer using * with the type, instead of variable name. For example, prefer int* ptr over int *ptr.

Pointers with assignments

We can use assignment operator for:

  1. Changing the variable pointer is pointing.
  2. Changing the value of the variable pointer is pointing.

Following example shows how to make pointer to point another object:

int* iptr{&value};
 
int anothervalue{10};
 
iptr = &anothervalue;

& address-of operator actually returns an object of type int* which is an int unnamed pointer object that we then assigned it to iptr.

Following example shows how to use pointer to change value of the object being pointed:

*iptr = 100;
 
std::cout << value;
std::cout << *iptr;

*iptr returns object value whose value then gets updated with 100.

References

  1. https://www.learncpp.com/cpp-tutorial/introduction-to-pointers/