c - 不理解 printf() 的奇怪行为
问题描述
我发现了一个要求输出以下语句的问题:
printf("%d"+1,123);
给出的答案是d
,它的解释是:既然"%d"
是字符串,这里的 +1 表示d
。
123
只是被忽略。我的第一个问题是:为什么123
会被忽略?
我还运行了以下语句
printf("%d"+2,123);
它什么也没打印。代码运行但没有错误。我的第二个问题是:为什么编译的代码没有错误?
第三次,我做了以下事情:
printf("%d"+0,123);
输出为123
. 所以我在这里变得很困惑。如果 +1 打印d
,那么不应该 +0 打印%
?
解决方案
想象一个字符串:
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
推荐阅读
- ssis - 使用 SSIS 在平面文件中写入重复行
- oracle - 无参数求解过程
- javascript - React:如何使用 onClick 添加无限数量的组件?
- ios - 如何最好地保持一个托管对象的映射到另一个在 Swift 中保持同步?
- sql - 如何在 SQL Server 中循环语句
- apache-flink - 维基百科编辑事件中标志的含义
- r - 计算多列总数的百分比
- android - 如何在 Android N 上为 NativeActivity 动态加载本机共享库(.so)?
- python - 从有向图创建无向图
- c# - 无法将 System.string 转换为 System.Byte[]