C++ - Pointers
In C++, pointer is an important concept to learn. There are few tasks which can be easily performed with the use of pointers and few other tasks like dynamic memory allocation which can not be performed without the use of pointers.
A pointer is a variable which stores address of another variable.
Address-of operator (&)
The address of a variable can be obtained by using ampersand sign &, known as Address-of operator followed by the name of a variable. See the syntax below:
Syntax
//pointer p1 which stores address of Var p1 = &Var;
Dereference operator (*)
The value of a variable can also be accessed by using pointer. The * operator, known as Dereference operator (also known as Indirection operator) followed by the name of the pointer gives the value stored in the address pointed by the pointer. Syntax for using this operator is given below:
Syntax
//p1 is a pointer of variable called Var //p1 stores address of Var //*p1 returns value of Var p1 = &Var; x = *p1;
Declare pointer
The declaration of a pointer starts with datatype pointed to by the pointer followed by * and name of the pointer. The datatype is not the datatype of the pointer itself, but the datatype of the data the pointer points to. See the syntax below:
Syntax
int *p1; //pointer to an integer double *p1; //pointer to a double float *p1; //pointer to a float char *p1; //pointer to a character //multiple declaration of pointers //p1 and p2 are pointers declared in a single line int *p1, *p2; //below, p1 is pointer //and p2 is integer datatype variable not pointer int *p1, p2
Example:
In the example below, an integer variable called MyVar and a pointer called p1 are created. pointer p1 is assigned the address of MyVar using address-of (&) operator. The dereference operator (*) is used with p1 to get the value of MyVar as shown in the output.
#include <iostream> #include <string> using namespace std; int main (){ int MyVar = 10; int *p1; p1 = &MyVar; cout<<"Address stored in p1 variable: "<<p1<<"\n"; cout<<"Value stored in *p1: "<<*p1; return 0; }
The output of the above code will be:
Address stored in p1 variable: 0x7ffe36221cd4 Value stored in *p1: 10