Pointers to Pointers in C

Pointers to Pointers in C


A pointer provides the address of the data item to which it points. The data item indicated by the pointer may be the address of another data item. Therefore, a given pointer can be a pointer to the pointer of any data item. To access the data element of a given pointer, we need two levels of indirect. First, the given pointer is de-reference to get the pointer to the given data item, and then second, the pointer is delayed to get the data item.

Let we understand with the help of example:

int i=5; Let we show in memory
Above diagram show i will take 4 byte of memory
int *p; let we show in memory
p=&i; let we show in memory
Now, If we write *p = 10;that means the value at x is updated form 5 to 10 that show in diagram.
int **q; let we show in memory
q = &p; let we show in memory
int ***s;
s = &q; let we show in memory
Now all the variable are stored in the memory at any particular memory address.That show in figure.

Let we see what the value stored in variables


printf("*p=%d",*p);
Output:*p=10

printf("*q=%d",*q);
Output:*q=101

printf("**q=%d",**q);
Output:**q=10

printf("**s=%d",**s);
Output:**s=101

printf("***s=%d",***s);
Output:***s=10

****s=20;
printf("i=%d",i);

Now here if write ***s=20 than the value of i become change from 10 to 20 show in the diagram.
So from the above examples we can easily understand how the pointer to pointer works and how we change value of any variable indirectly or de referencing the pointers variables.


Example: Write a program to declare the pointer to pointer variable and to display the elements of pointer.


Copy Code
#include <stdio.h>
#include <conio.h>

void main()
{
    int a;
    int *ptr1;
    int **ptr2;
    a=100;
    printf("a=%d\n",a);
    ptr1=&a;
    ptr2=&ptr1;
    printf("First pointer=%d\n",*ptr1);
    printf("Second pointer=%d\n",**ptr2);
    getch();
}

Output:

a=100
First pointer=100
Second pointer=100

Know more about pointers


No comments:

Post a Comment