Pointers in C++

In  a  C++ programming language, variable is used to hole the value & this variable stored in a memory. 

Each variable has a address to identify where these variables actually stored in a memory.  

 In a C++  programming language, pointer is a variable which can hold the address of another variable.  

 Accessing Address of Variable

In a system every memory location has its address & we can access the address using ampersand (&) operator.

This ampersand (&) operator  denotes an address in memory. 

Ex:   int  i = 20;
      char c = ‘a’;

In the above example, there are two variable i & c.

Integer variable “i” stores the value 10 at memory location 1024(for example) and character variable “c” stores the value ‘a’ at memory location 1026.

cout<<“\n value of  variable i=  “<<  i ;
cout<<“\n value of  variable c=  “<< c ;

Output

value of  variable i= 20
value of  variable c= a

If we want to print the address of variable ‘i and c’ then we need ampersand (&) operator  .

   cout<<“\n Address of  variable i =  “<< &i ;
   cout<<“\n Address of  variable c= “<< &c ;

Output:           Address of  variable i =   1024
                        Address of  variable c=   1026

Note: When you run this program, address are printed might be different.Example: Write a program to print the address of the variable.

#include using namespace std;

Output

Note: Each and every time when you run this program these variables stored in a different memory location.

Pointer Variable

pointer  variable is hold the address of another variable.

Output

Value at address

In the above example, there are two variable, first is normal variable ‘i’ & pointer variable ‘ptr’.

Integer variable “i” stores the value 10 at memory location 1024(for example) and pointer variable “ptr” stores the address of variable  ‘i’ at memory location 3045.

Example:

#include

Output:

value of  variable i=  10

Note: Pointer variable “ptr” prints the address of variable and “*ptr” prints the value of i. *variable name (*ptr) is also called value at address.

Example:

Output

Note: When you run this program, address are printed might be different.

Pointer to Pointer

In a C language, a pointer is an address. Normally, a pointer variable contains the address of a another variable. 

A pointer to a pointer is a chain of pointers. 

Or

Pointer to pointer means one pointer variable holds the address of another pointer variable.

Example:

Output

NULL Pointers

A pointer that is assigned NULL is called a null pointer. We must initialize NULL pointer during variable declaration.

A null pointer refers to pointer variable that does not point to a valid address.

Generally NULL pointer is used when you do not have an exact address to be assigned.

Output

Categories C++