[英]Why does the printed char change when I use printf with %s and %c?
This is the code I have: 这是我的代码:
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));
}
and the output I get is: 我得到的输出是:
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
When I change the last statement to: 当我将最后一条语句更改为:
printf("%c",*(&p));
The last line printed will be: 最后打印的行将是:
6
instead of 代替
koraytugay
But why? 但为什么? I am expecting that it would print
我希望它会打印
k
? ?
%c
format specifier expects an argumnet of type char
. %c
格式说明符期望使用char
类型的argumnet。
In your code, *(&p)
is of type char *
. 在您的代码中,
*(&p)
的类型为char *
。 Using %c
to print that leads to undefined behaviour . 使用
%c
打印会导致未定义的行为 。
Reference: From chapter 7.21.6.1, C11
standard, paragraph 9, 参考:从第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.
如果任何参数都不是相应转换规范的正确类型,则行为未定义。
It doesn't print k
because it's expecting a char
and you passed a char *
so probably 它不会打印
k
因为它期待一个char
并且您通过了char *
所以很可能
printf("%c", **(&p));
will print k
. 将打印
k
。
The type of &p
is char **
because it creates a pointer with the address of p
, so *(&p)
is exactly the same as p
, hence to print *(&p)
you need the "%s"
specifier. 该类型的
&p
是char **
,因为它会创建的地址的指针p
,所以*(&p)
是完全一样p
,因此打印*(&p)
你所需要的"%s"
符。
If you use the "%c"
specifier with *(&p)
it's evaluated as an integer so you can't predict what is going to be printed because it will depend on what is the value stored in the pointer. 如果在
*(&p)
使用"%c"
说明符,则将其视为整数,因此您将无法预测将要打印的内容,因为它取决于指针中存储的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.