我正在尝试理解指针相关的内容,因此我写了这段代码:
#include <stdio.h>
int 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
必须是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*
(数组第一个元素)的指针。 - Cholthi Paul Ttiopic