我发现了一个问题,要求输出以下声明:
printf("%d"+1,123);
Run Code Online (Sandbox Code Playgroud)
给出的答案是d,它的解释是:既然"%d"是一个字符串,这里的+1表示d.
123只是被忽略了.我的第一个问题是:为什么123会被忽视?
我还运行了以下声明
printf("%d"+2,123);
Run Code Online (Sandbox Code Playgroud)
它什么都没打印.代码运行但没有错误.我的第二个问题是:为什么代码编译没有错误?
第三次,我做了以下事情:
printf("%d"+0,123);
Run Code Online (Sandbox Code Playgroud)
输出是123.所以我在这里变得非常困惑.如果+1打印d,那么不应该+0打印%?
想象一个字符串:
char str[] = "%d";
Run Code Online (Sandbox Code Playgroud)
现在我们知道:
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
Run Code Online (Sandbox Code Playgroud)