我试图用指针理解一些东西,所以我写了这段代码:
#includeint main(void) { char s[] = "asd"; char **p = &s; printf("The value of s is: %p\n", s); printf("The direction of s is: %p\n", &s); printf("The value of p is: %p\n", p); printf("The direction of p is: %p\n", &p); printf("The direction of s[0] is: %p\n", &s[0]); printf("The direction of s[1] is: %p\n", &s[1]); printf("The direction of s[2] is: %p\n", &s[2]); return 0; }
用gcc编译时我得到以下警告:
$ gcc main.c -o main-bin -ansi -pedantic -Wall -lm main.c: In function ‘main’: main.c:6: warning: initialization from incompatible pointer type main.c:9: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char (*)[4]’ main.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char **’ main.c:12: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char ***’
(gcc的标志是因为我必须是C89)
为什么不兼容的指针类型?数组的名称不是指向它的第一个元素的指针吗?所以,如果s是指向'a'的指针,那么&s
必须是a char **
,不是吗?为什么我会收到其他警告?我是否必须使用(void *
)转换指针才能打印它们?
跑步的时候我得到这样的东西:
$ ./main-bin The value of s is: 0xbfb7c860 The direction of s is: 0xbfb7c860 The value of p is: 0xbfb7c860 The direction of p is: 0xbfb7c85c The direction of s[0] is: 0xbfb7c860 The direction of s[1] is: 0xbfb7c861 The direction of s[2] is: 0xbfb7c862
s的价值和它的方向(当然还有价值p
)如何相同?
"s"不是"char*",它是"char [4]".所以,"&s"不是"char**",而是"指向4个字符阵列的指针".您的编译器可能会将"&s"视为您编写了"&s [0]",这大致相同,但它是"char*".
当你写"char**p =&s;" 你试图说"我希望将p设置为当前指向"asd"的东西的地址.但是目前没有任何东西指向 "asd".只有一个数组保存 "asd";
char s[] = "asd"; char *p = &s[0]; // alternately you could use the shorthand char*p = s; char **pp = &p;
是的,您的编译器期望void*.只是把它们变成无效*.
/* for instance... */ printf("The value of s is: %p\n", (void *) s); printf("The direction of s is: %p\n", (void *) &s);