Categories: C

Pointer to Pointer in C

A pointer variable stores the address of another pointer variable; this is referred to as a pointer to a pointer variable in C.

It is a type of multiple indirections, also known as a chain of pointers. A pointer contains the address of a variable, and when a pointer to a pointer is defined, the first pointer contains the address of the second pointer, which points to the actual variable’s address.

Let us understand this better with the help of an example:

int b=10;
int *p=&b;
int **ptr=&p;

here:

  • a variable b has a value of 10,
  • p is an integer pointer that points to b i.e, stores the address of variable b
  • then we have another integer pointer ptr which points towards pointer p, i.e, stores the memory location of pointer p.

Using ptr we can now access the pointer p as well as the value of variable b.

Example:
#include<stdio.h>
int main()
{

   int  b;
   int  *p;
   int  **ptr;

   b = 10;

   /* take the address of b */   p = &b;

   /* take the address of p using address of operator & */   ptr = &p;

   /* take the value using ptr */   printf("Value of b = %d\n", b );
   printf("Value available at *p = %d\n", *p );
   printf("Value available at **ptr = %d\n", **ptr);
    /* take the address  */   printf("Value of &b = %u\n", &b );
   printf("Value available at p = %u\n", p );
   printf("Value available at &p = %u\n", &p );
    printf("Value available at &ptr = %u\n", &ptr);
    printf("Value available at ptr = %u\n", ptr);
   printf("Value available at *ptr = %u\n", *ptr);

   return 0;
}
Output:
Value of b = 10
Value available at *p = 10
Value available at **ptr = 10
Value of &b = 2051687924
Value available at p = 2051687924
Value available at &p = 2051687928
Value available at &ptr = 2051687936
Value available at ptr = 2051687928
Value available at *ptr = 2051687924

Note: also read about the Pointer to structure

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 days ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

2 weeks ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 weeks ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 month ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 month ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

1 month ago