Reputation: 5960
I was trying to understand simple pointers a little better by clarifying for myself the address a pointer points to, the address of the pointer itself and the value the address refers to. So I wrote a small piece of code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int *p;
int **pp;
a = 42;
/* Take the address of a */
p = &a;
/* Take the address of p */
pp = &p;
printf("Address of int &a: %p\n\n", &a);
printf("value of a: %d\n\n", a);
printf("Address where *p points to via (void *)p: %p\n\n", (void *)p);
printf("Value that *p points to via *p: %d\n\n", *p);
printf("Address of *p itself via (void *)&p: %p\n\n", (void *)&p);
printf("Address where **p points to via (void *)pp: %p\n\n", (void *)pp);
printf("Value that **pp points to via **pp: %d\n\n", **pp);
printf("Address of **p itself via (void *)&pp: %p\n\n", (void *)&pp);
return EXIT_SUCCESS;
}
This all works as expected (Please, do correct me if I made any mistakes here.). Now, I want to go one level deeper and use a pointer to a pointer to pointer ***ppp
and assign it the address the pointer to pointer pp
points to which is the address *p
points to which is the address of a
. Here is how I thought I could do it:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int *p;
int **pp;
int **ppp;
a = 42;
/* Take the address of a */
p = &a;
/* Take the address of p */
pp = &p;
ppp = &pp;
printf("Address of int &a: %p\n\n", &a);
printf("value of a: %d\n\n", a);
printf("Address where *p points to via (void *)p: %p\n\n", (void *)p);
printf("Value that *p points to via *p: %d\n\n", *p);
printf("Address of *p itself via (void *)&p: %p\n\n", (void *)&p);
printf("Address where **pp points to via (void *)pp: %p\n\n", (void *)pp);
printf("Value that **pp points to via **pp: %d\n\n", **pp);
printf("Address of **pp itself via (void *)&pp: %p\n\n", (void *)&pp);
printf("Address where ***ppp points to via (void *)ppp: %p\n\n", (void *)ppp);
printf("Value that ***ppp points to via ***ppp: %d\n\n", ***ppp);
printf("Address where ***ppp points to via (void *)&ppp: %p\n\n", (void *)&ppp);
return EXIT_SUCCESS;
}
But this gives me an incompatible pointer warning. Could someone explain to me why this does not work and if the calls to printf()
are right?
Upvotes: 1
Views: 98
Reputation: 2822
The problem is here:
int **ppp;
That should be
int ***ppp;
As it is now your trying to force a triple pointer, into a double pointer. Which will probably gives you an error on this line:
ppp = &pp;
Also you might want to have a look at number 2 of this article:).
P.s. For future reference, if you provide a line number and specific error. People might want to help you even better and more:)
Upvotes: 2
Reputation: 31
The error is in this line int **ppp; /* It should be ***ppp, because you're pointing to a pointer which points to another one*/
Upvotes: 3