Array of pointers in C/C++


Array of pointers

Like array of variables, we can declare array of pointers in c where each pointer further points to another array. Code is given below

int a[3= {4,7,8};
int b[4= {7,12,34,2};
int x = 10;
int *ptr[3= {a,b,&x};

In above lines, two int arrays are declared and initialized and one variable x is declared. In last line, an array of pointers is declared and initialized with two const pointers (names of two int arrays) and memory address of variable x using & operator.

Using this array of pointers we can access all elements of any array. Below code will display output as memory address of first element of both arrays respectively and value of x variable because array name contains the memory address of first element.

cout<<a<<b<<x;

We can also get above code output using ptr as

cout<<ptr[0]<<ptr[1]<<ptr[2];

ptr[0] means first element of pointer's array which is name of first int array.
ptr[1] means second element of pointer's array which is name of second int array
ptr[2] means third element of pointer's array which is memory address of variable x

If we simply use dereference operator with all, we will go to the particular value as 

cout<<*ptr[0]<<*ptr[1]<<*ptr[2];

*ptr[0] will show value of first element of first array
*ptr[1] will show value of first element of second array
*ptr[2] will show value of variable x

How to access all elements of arrays

For this increment pointer to jump to next element as below line gives memory addresses of all elements of first array

cout<<ptr[0];
cout<<ptr[0]+1;
cout<<ptr[0]+2;

ptr[0] is memory address of first element of first array
ptr[0]+1 is memory address of second element of first array
ptr[0]+2 is memory address of third element of first array

And by dereferencing all above we get values of all elements of first array
cout<<*(ptr[0]);
cout<<*(ptr[0]+1);
cout<<*(ptr[0]+2);

*(ptr[0]) gives value of first element of first array
*(ptr[0]+1) gives value of second element of first array
*(ptr[0]+2) gives value of third element of first array

Similarly we can get addresses and values of all elements of second array as below
cout<<ptr[1];
cout<<ptr[1]+1;
cout<<ptr[1]+2;
cout<<ptr[1]+3;

cout<<*(ptr[1]);
cout<<*(ptr[1]+1);
cout<<*(ptr[1]+2);
cout<<*(ptr[1]+3);

Below is a C++ Program in which an array of pointers c++ is used to manipulate two arrays and one variable

array of pointers in c
Array of pointers in C/C++
 Output
array of pointers in c output
Array of pointers in C output

No comments:

Post a Comment