Programming

 Pointers In C++…

 Pointers In C++

 

As we know everything in a computer is stores in memory and that thing has an address. So, C++ give us the datatype pointers which stores the address of other variable, objects or arrays. Pointer also can point to other pointers. The major use of pointers is to make dynamic arrays. You can get the address of any variable by adding a single symbol “&”.

Syntax:

Datatype *variableName;

 

Pointer of integer:

int val;

int *ptr = &val;

Addresses of pointer 0x2600
Value 0x0564

 

Pointer of char:

char val;

char *ptr = &val;

Addresses of pointer 0x2604
Value 0x0568

 

Pointer of double:

double val;

double *ptr = &val;

Addresses of pointer 0x2605
Value 0x0569

 

Like this we can make different pointers of different of datatype. We can also point the pointer to the arrays too.

 

 

 

Pointer points at array of integer:

int val[5];

int *ptr = &val;

Addresses of pointer 0x2600
Value 0x0564

 

Pointer points at array of char:

char val[8];

char *ptr = &val;

Addresses of pointer 0x2604
Value 0x0568

 

Pointer points at array of double:

double val[10];

double *ptr = &val;

Addresses of pointer 0x2605
Value 0x0569

 

Example1:

#include <iostream>

using namespace std;

 

int main ()

{

int var = 10;

int* ptr = &var;

 

cout << “Address of Ptr:  ” << &ptr << endl;

cout << “Address stored int Ptr:   ” << ptr << endl;

cout << “Value at address in Ptr:  ” << *ptr;

}

 

 

Example2:

#include <iostream>

using namespace std;

 

int main ()

{

char var = ‘P’;

char* ptr = &var;

 

cout << “Address of Ptr:  ” << &ptr << endl;

cout << “Address stored int Ptr:   ” << ptr << endl; //We can’t get the address of char like this.

cout << “Value at address in Ptr:  ” << *ptr;

}

 

 

Example3:

#include <iostream>

using namespace std;

 

int main ()

{

double var = 9.56;

double* ptr = &var;

 

cout << “Address of Ptr:  ” << &ptr << endl;

cout << “Address stored int Ptr:   ” << ptr << endl;

cout << “Value at address in Ptr:  ” << *ptr;

}

 

 

Example4:

#include <iostream>

using namespace std;

 

int main ()

{

int var[5] = {5, 6, 7, 8, 9};

int* ptr = &var;

 

cout << “Address of Ptr:  ” << &ptr << endl;

cout << “Address stored int Ptr:   ” << ptr << endl;

cout << “Values: “;

 

for(int counter = 0; counter < size; counter++)

{

cout << ptr[counter] << ” “;

}

}

 

1 Comment

1 Comment

  1. Ghumman

    March 3, 2020 at 3:45 pm

    Nice understanding…

Leave a Reply

Your email address will not be published.

Most Popular

To Top