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

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago