CodesJava

Easy learning with example program codes

CPP Pointers


CPP pointers can be defined as a variable, pointing towards the address of a value.

Syntax:

Data_type *variable_Name;

CPP Pointer to Pointer:

When a pointer refers to the address of another pointer, it is called as Pointer to Pointer in CPP.

Syntax:

Data_type **variable_Name;

Pointer Arithmetic in C:

CPP also facilitates Arithmetic operations with Pointers. Some of these are:

CPP Pointer Increment:

Incrementing a pointer in CPP simply means to increase the pointer value step by step to point to the next location.

Logic:

Next Location = Current Location + i * size_of(data type)

CPP Pointer Decrement:

Decrementing a pointer in CPP simply means to decrease the pointer value step by step to point to the previous location.

Logic:

Next Location = Current Location – i * size_of(data type)

CPP Pointer Addition:

Addition in pointer in CPP simply means to add a value to the pointer value.

Logic:

Next Location = Current Location + (Value To Add * size_of(data type))

CPP Pointer Subtraction:

Subtraction from a pointer in CPP simply means to subtract a value from the pointer value.

Logic:

Next Location = Current Location – (Value To Add * size_of(data type))

 

Advantages of using Pointers in CPP:

  • Improves the performance.
  • Frequently used in arrays, structures, graphs and trees.
  • Less number of lines needed in a code.
  • Useful in accessing any memory location.
  • Used in Dynamic Memory Allocation.

NULL Pointer:

NULL pointers either have no value or NULL value assigned to it.

 

Example 1: Example of Pointers used inside a function.

#include <iostream.h>
using namespace std;
 
int sum(int *a, int *b)
{
int *c;
*c = *a + *b;
return *c;
}
 
int main()
{
int x = 100;
int y = 200;
int add;
add = sum(&x,&y);
cout << x <<" + " << y << " = " << add;
return 0;
}

Output

100 + 200 = 300

Example 2: Example of CPP Pointer to Pointer.

#include <iostream.h>
using namespace std;
 
int main()
{  
int n = 60784; 	 
int *a;
int **b;    
a = &n;    
b = &a;    
 
cout << n <<endl;
cout << a <<endl;
cout << b <<endl;
cout << &n <<endl;
cout << &a <<endl;
return 0;
}

Output

60784                                
0x7ffc8ab9d354                  
0x7ffc8ab9d358                         
0x7ffc8ab9d354                      
0x7ffc8ab9d358
Please follow and like us:
Posted in CPP   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki