谁能解释一下这段代码中发生了什么?
#include <stdio.h>
void f(const char * str) {
printf("%d\n", str[4]);
}
int main() {
f("\x03""www""\x01""a""\x02""pl");
f("\x03www\x01a\x02pl");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么是输出?
1
26
Run Code Online (Sandbox Code Playgroud)
问题在于"\x01""a"vs "\x01a",以及 hex->char 转换和字符串连接发生在词法处理的不同阶段的事实。
在第一种情况下,十六进制字符在连接字符串之前被扫描和转换,因此第一个字符被视为\x01. 然后将"a"连接起来,但是已经进行了hex->char的转换,连接后没有重新扫描,所以得到两个字母
\x01和a。
在第二种情况下,扫描仪将其\x01a视为单个字符,ASCII 代码为 26。