Login    New User    Forgot Password    Help      

Pointer

GO TO INDEX

Pointer

A pointer is a variable that is used to store a memory address. The address is the location of the variable in the memory. Pointers help in allocating memory dynamically. Pointers improve execution time and saves space.  Pointer points to a particular data type. The general form of declaring pointer is:-

 

            type *variable_name;

 

type is the base type of the pointer and variable_name is the name of the variable of the pointer. For example,

 

            int *x;

 

x is the variable name and it is the pointer of type integer.  

Pointer Operators

 

There are two important pointer operators such as ‘*’ and ‘&’. The ‘&’ is a unary operator. The unary operator returns the address of the memory where a variable is located.  For example,

 

            int x*;

            int c;

            x=&c;

 

variable x is the pointer of the type integer and it points to location of the variable c. When the statement

                       

                        x=&c;

 

is executed, ‘&’ operator returns the memory address of the variable c and as a result x will point to the memory location of variable c.

 

The ‘*’ operator is called the indirection operator. It returns the contents of the memory location pointed to.  The indirection operator is also called deference operator. For example,

 

            int x*;

            int c=100;

            int p;

x=&c;

            p=*x;

 

variable x is the pointer of integer type. It points to the address of the location of the variable c. The pointer x will contain the contents of the memory location of variable c. It will contain value 100. When statement

                       

p=*x;

 

is executed, ‘*’ operator returns the content of the pointer x and variable p will contain value 100 as the pointer x contain value 100 at its memory location.  Here is a program which illustrates the working of pointers.

Example of pointer

#include <iostream>
 
 int main()
 {
     unsigned short int intValue = 5, yourAge = 10;
     unsigned short int * intPointer = &intValue;  // a pointer
 
     std::cout << "intValue:\t" << intValue;
     std::cout << "\t\tyourAge:\t" << yourAge << "\n";
     std::cout << "&intValue:\t" << &intValue;
     std::cout << "\t&yourAge:\t" << &yourAge <<"\n";
 
     std::cout << "intPointer:\t" << intPointer << "\n";
     std::cout << "*intPointer:\t" << *intPointer << "\n\n";
 
     intPointer = &yourAge;       // reassign the pointer
 
     std::cout << "intValue:\t" << intValue;
     std::cout << "\t\tyourAge:\t" << yourAge << "\n";
     std::cout << "&intValue:\t" << &intValue;
     std::cout << "\t&yourAge:\t" << &yourAge <<"\n";
 
     std::cout << "intPointer:\t" << intPointer << "\n";
     std::cout << "*intPointer:\t" << *intPointer << "\n\n";
 
     std::cout << "&intPointer:\t" << &intPointer << "\n";
     return 0;
 }

 

Output

Pointer

GO TO INDEX