这是我的代码:
int main(){
char *p = "koraytugay";
printf("%s%i byte(s).\n", "Size of variable p:" ,sizeof(p));
printf("%s%i byte(s).\n\n", "Size of what p points to:" ,sizeof(*p));
char t[] = "koraytugay";
printf("%s%i byte(s).\n", "Size of variable t:" ,sizeof(t));
printf("%s%i byte(s).\n\n", "Size of what t points to:" ,sizeof(*t));
printf("%s%c\n", "Printing p[3]: ", p[3]);
printf("%s%c\n", "Printing t[3]: ", t[3]);
printf("%s",*(&p));
}
我得到的输出是:
Size of variable p:8 byte(s).
Size of what p points to:1 byte(s).
Size of variable t:11 byte(s).
Size of what t points to:1 byte(s).
Printing p[3]: a
Printing t[3]: a
koraytugay
当我将最后一条语句更改为:
printf("%c",*(&p));
打印的最后一行将是:
6
代替
koraytugay
但是为什么?我期待它会打印
k
?
最佳答案
%c
格式说明符需要 char
类型的参数。
在您的代码中,*(&p)
的类型为 char *
。使用 %c
打印导致 undefined behaviour .
引用:来自第 7.21.6.1 章,C11
标准,第 9 段,
If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
关于c - 为什么当我将 printf 与 %s 和 %c 一起使用时,打印的字符会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29076618/