Understanding pointer-to-pointer in c

For discussions about programming, and for programming questions and advice


Moderator: Forum moderators

Post Reply
User avatar
user1234
Posts: 413
Joined: Sat Feb 26, 2022 5:48 am
Location: Somewhere on earth
Has thanked: 154 times
Been thanked: 88 times

Understanding pointer-to-pointer in c

Post by user1234 »

So I wanted to understand pointers-to-pointers in c, especially when using linked lists.

What I have assumed a pointer to be, is that it is a space in PC's ram that has been used to save addresses of other spaces (variables).

Is that correct? And if it is correct then how would you define pointer-to-pointer?

Thanks!

PuppyLinux 🐾 gives new life to old computers ✨

User avatar
rockedge
Site Admin
Posts: 5816
Joined: Mon Dec 02, 2019 1:38 am
Location: Connecticut,U.S.A.
Has thanked: 2073 times
Been thanked: 2167 times
Contact:

Re: Understanding pointer-to-pointer in c

Post by rockedge »

That is correct.

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value

Example code:

Code: Select all

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

   int  var;
   int  *ptr;
   int  **pptr;

   var = 3000;

   /* take the address of var */
   ptr = &var;

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

   /* take the value using pptr */
   printf("Value of var = %d\n", var );
   printf("Value available at *ptr = %d\n", *ptr );
   printf("Value available at **pptr = %d\n", **pptr);

   return 0;
}

When compiled and run the code produces:

Code: Select all

Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
some1
Posts: 71
Joined: Wed Aug 19, 2020 4:32 am
Has thanked: 17 times
Been thanked: 11 times

Re: Understanding pointer-to-pointer in c

Post by some1 »

Post Reply

Return to “Programming”