Pointers in Cpp

Pointers in Cpp

What is Pointer ?

A pointer is a special variable whose value is the address of another variable. In simple word, Pointer is also kind of a variable that is used to store address of variables or a memory location.

How to initialize a Pointer ?

Defining Pointer is a step-by-step procedure, like this ->

Step 1: Defining a Pointer Variable
We need to define a Pointer variable first by specifying the data type and variable name.
Syntax : 

data_type *pointer_var;
Example : 

int *p;

//Here int is the data type of the pointer variable and ‘p’ is the name of that variable.
//The ‘*’ (asterisk) sign is used to declare the pointer.

Step 2: Assigning the Value
After declaring we need to assign the address of a variable to the pointer variable.
Syntax : 

pointer_var = &main_var;

Example : 
p = &var;

//Here ‘p’ is the pointer variable and ‘var’ is the name of that variable whose address is being stored.
//The ‘&’ (asterisk) sign is used to assign the address to a pointer.

A sample program of usage of Pointer Variable :

#include <iostream>
using namespace std;

int main() 
	int Eruditors = 47;
	int *p;
	p = &Eruditors;
	//Instead of declaring & assigning separately we can declare & assign a pointer only once. For example,
	//int *p = &Eruditors;

	cout << "Value of Eruditors Variable : " << Eruditors << endl;
	//Value assigned in int Eruditors variable

	cout << "Value of *p Variable : " << *p << endl;
	//Value of *p variable that indicates to the value of Eruditors variable

	cout << "Address stored in p Variable : " << p << endl;
	// Accessing the address using pointer variable

	cout << "Address of Eruditors Variable : " << &Eruditors << endl;
	//Accessing the address without using pointer variable
	return 0;

Output :

Key Points about Pointer : 

  • ~ At the time of initializing, we can assign the 'NULL' value in a pointer variable. It assigns '0'. For example, int *p = NULL;
  • ~ Four arithmetic operators that can be used in pointers: ++, --, +, -
  • ~ C++ allows us to have pointer on a pointer and so on.

Advantages of an Pointer in C++ : 

  • ~ It reduces the code and improves the performance.
  • ~ We can get access of any memory location access by pointer.
  • ~ A pointer can be used to Arrays and Functions also.