上記の図は、ポインタへのポインタのメモリ表現を示しています。第1ポインタptr1(あなたの場合は)は、第2ポインタptr2のアドレスを格納し、第2ポインタptr2(あなたの場合はP1
)は変数のアドレスを格納します。
#include <stdio.h>
#include <stdlib.h>
typedef struct _s {
int data;
} Tree;
int main(int argc, char *args[])
{
/*
* Arrow operator example
* foo->bar is equivalent to (*foo).bar
* it gets the member called 'bar' from the struct that 'foo' points to.
*/
Tree **P2,*P1;
P1 = (Tree*)malloc(sizeof(Tree));
P1->data = 789;
//P1=&P2; // It's wrong, Incompatible pointer types Tree* and Tree***
P2 = &P1; // It's right, p2 points to address of p1
printf("%d\n", (*P2)->data); // same as (**P2).data
printf("%p\n", (void*) &(*P2)->data); // same as &(**P2).data, (void* casting to print address)
printf("%d\n", P1->data); // same as (*P1).data
//printf("%d",*P1->data); // same as *(P1->data), it's already dereferenced type, you're trying to dereference again??
free(P1);
return 0;
}
出典
2018-02-13 11:59:49
snr