C++ Pointers


Pointer is a variable which stores the address of another variable.

A pointer can also store the address of another pointer which is called chain of pointer.

The values of variable are read through thepointer.

Since the pointer locates the address immediately the process time is considerably reduced.

The data type of the pointer variable must be same as the data type of variable.

Remember pointer is a variable so it has also address.

Syntax

type *varname;

Pointers are variables that contain memory addresses as their values.

A variable name directly references a value.

A pointer indirectly references a value. Referencing a value through a pointer is called indirection.

A pointer variable must be declared before it can be used.


Declaration of pointer

Pointer can be declared in these three methods.

Method 1: int *p;

Method 2: int* p;

Method 3: int * p;


Simple Pointers

Pointer is a value that points to a location in the memory

Pointer is associated with a type

int number ;
	int * ptr_num ;
	number = 23;
	ptr_num = & number;
	cout<<"Value is"<<*ptr_num;

As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory.

Consider the following which will print the address of the variables defined:

Example

#include <iostream>
using namespace std;
int main ()
{
   int  var1;char var2[10];
   cout <<"Address of var1 variable: ";
   cout <<&var1 << endl;
   cout <<"Address of var2 variable: ";
   cout <<&var2 << endl;
   return0;
}
Output
Address of var1 variable: 0xbfedfb45
Address of var2 variable: 0xbfedfb21

Example of Pointer

 #include <iostream>
using namespace std;
 int  main ()
{ 
int  x; // A normal integer
  int *p; // A pointer to an integer
  p = &x; // Read it, "assign the address of x to p"
  cin>> x; // Put a value in x, we could also use *p here
  cout<< *p <<"\n"; // Note the use of the * to get the value
}

Share this article on