首页 > 解决方案 > 不理解 printf() 的奇怪行为

问题描述

我发现了一个要求输出以下语句的问题:

printf("%d"+1,123);

给出的答案是d,它的解释是:既然"%d"是字符串,这里的 +1 表示d

123只是被忽略。我的第一个问题是:为什么123会被忽略?

我还运行了以下语句

printf("%d"+2,123);

它什么也没打印。代码运行但没有错误。我的第二个问题是:为什么编译的代码没有错误?

第三次,我做了以下事情:

printf("%d"+0,123);

输出为123. 所以我在这里变得很困惑。如果 +1 打印d,那么不应该 +0 打印%

标签: c

解决方案


想象一个字符串:

char str[] = "%d";

现在我们知道了:

str[0] == '%'
str[1] == 'd'
str[2] == '\0' = 0x00
str+2 == &str[2] == the address of the byte 0x00 inside the str string == ""
printf("%d", 123); is the same as printf(str, 123)
printf("%d" + 2, 123); if the same as printf("", 123); and it will print "", ie. nothing

推荐阅读