How to use Pointers Using C++ Language in DEV C++

Pointers:

"Pointer is a variable which has the address of memory location of another variable".

Like variables and constants, pointers are also defined first then we use it.

Initialization:

type *variable;

type: any valid c++ data type
*     : asterisk sign to ensure that it is pointer variable
variable name:  variable name of pointer 

Now in order to understand the use of pointers, we should know about that what are addresses and how can we access them. Lets talk about it.

Addresses of Variables:
Every variable defined has its own memory location which has its own address. These addresses can be find out by using ampersand (&) operator. Figure will help you understand this


        x
Memory cells รจ

       10


   0x28fefc

In above you can consider the memory locations like memory cells. I am showing that there is integer variable named x has assigned a value 10 in the memory location which has address 0x28fefc. Every memory cell has its own address.Now i explain this through example how to get address memory location.

Program code:

#include<iostream.h>

int main()
{
      int a=2;                            // integer variable a
      int b[];                             // integer array named b

     cout<<"address of integer variable a = "<<&a<< endl<<endl;    
     cout<<"address of integer array b    = "&b<<endl;        

getch();

}

Note: For finding the address of array, just write array name with ampersand operator , do not include square brackets.

Output:



How to use Pointers:
I will show this in three steps. First define pointer and any other variable. Second assign pointer variable  the address of other variable. Third access the value of variable direct from the memory location or you can say that address.

Program code:

#include<iostream>
using namespace std;
int main ()
{
    int   x = 2 ;
    int *p;
    p = &x ;
    
cout<<"Value of integer variable x                              =   "<< x <<endl;
cout<<"Address of integer variable x                          =   "<<  p <<endl;
cout<<"Accessing value of x using pointer variable *p =   "<< *p<<endl;

getch();

}

Note:
*p gives you the value of variable x
  p gives you his address location

Output: After program code is  compiled and executed the output of this program will be look like this

Output


2 comments:

Please disable your ad blocker to support this website.

Our website relies on revenue from ads to keep providing free content.