throw233 throw233 - 6 months ago 39
C Question

Understanding Pointer to Pointer Logic in C

I came across this code and was a bit confused on exactly what's going on here:

int **p;
p = malloc(sizeof(int *));
*p = malloc(sizeof(int));

**p = 10;


First of, p is a pointer to a pointer but it doesn't point to anything else, so why would we have to malloc twice here? Also in the first malloc call, why does one not need to have two pointer values around the p:
for instance:

**p = malloc(sizeof(int *));

instead of :

p = malloc(sizeof(int *));

I understand that the next line deference's the pointer and stores the value 10 in it, and then prints it. However I don't really get the previous lines, or at least why they're done in that frame of mind.

I'm used to seeing double pointers in this mindset:

int main(void) {
int *ptr;
int **ptr_ptr;

ptr = malloc(sizeof(int));

*ptr = 5;
ptr_ptr = &ptr;

printf("%d\n",**ptr_ptr); /*prints 5*/

return 0;

As the double pointer actually points to something here. Any help with the first bit of code would be much appreciated.


As int **p is a pointer to pointer, it will hold the location or address of an int* type of pointer. But one must first allocate enough memory for the int* which will be stored at the location pointed by p. This line does this job, it initializes p:

p = malloc(sizeof(int *));

Now, that int*'s location is known, one must allocate memory to store an acutal int at the memory pointed by *p which is our int* pointer. So another malloc() call is needed to initialize the int* type pointer.

*p = malloc(sizeof(int));

When all of it is done, an integer can be assigned to **p, which is the int pointed by *p:

**p = 10;