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 valuestd::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:
Changing the variable pointer is pointing.
Changing the value of the variable pointer is pointing.
Following example shows how to make pointer to point another object: