请注意,C 标准定义main() 程序返回int,而不是void。
给定代码:
#include <stdio.h>
int main()
{
char str[2][7] = {"1234567", "abcdefg"};
char** p = str;
printf("%d\n", *(p+1));
printf("%c\n", *(p+1));
return(0);
}
使用gcc -o x -Wall x.c 编译时,您会收到警告:
x.c: In function ‘main’:
x.c:5: warning: initialization from incompatible pointer type
x.c:6: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘char *’
x.c:7: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’
(如果省略-Wall,则不会收到格式警告。)
这告诉您您正在传递一个指向printf() 的指针。打印指针不会那么有用。但是,前面的警告还告诉您,您错误地初始化了变量p。然而,最终结果是p 指向str 中空间的开始。打印时
一个有趣的小怪癖:通常,诸如“1234567”之类的字符串包含终止NUL '\0';在您的数组中,因为您指定数组的长度是 7,而不是 8,所以缺少终止的空值。小心你如何打印字符串!
这是代码的另一个变体:
#include <stdio.h>
int main()
{
char str[2][7] = {"1234567", "abcdefg"};
char** p = str;
printf("%d\n", *(p+1));
printf("%c\n", *(p+1));
printf("%p %p %p -- %p %p %p\n", str, &str[0], &str[0][0], p, p+1, *(p+1));
printf("%.4s\n", (p+1));
return(0);
}
这给了我以下输出(来自 Mac):
1631008309
5
0xbffffa5e 0xbffffa5e 0xbffffa5e -- 0xbffffa5e 0xbffffa62 0x61373635
567a
请注意,地址 str、&str[0] 和 &str[0][0] 都具有相同的值,并且p+1 是四个字节。当被视为字符串时,它会打印第一个初始化程序的最后三个字节和第二个初始化程序的第一个字节。
另外,为了好玩,用gcc -m64 -o x64 x.c编译,输出为:
1701077858
b
0x7fff5fbff9e0 0x7fff5fbff9e0 0x7fff5fbff9e0 -- 0x7fff5fbff9e0 0x7fff5fbff9e8 0x676665646362
bcde