我使用以下online C compiler 来运行您的代码,
结果如下:
1. 4195988 - undefined behaviour (UB), manifesting here as the address
of the char array as you stated (for a 64 bit address you might or
might not get truncation)
2. 49 - ASCII value of '1'
3. � - undefined behaviour, manifesting here as unsupported ASCII value
for a truncation of the address of the array of chars
(placing 32-bit address into a char - assuming a 32-bit system)
4. 1 - obvious
5. 2 - obvious
6. 12345 - obvious
7. Segmentation fault - undefined behaviour, trying to place the first char
of a char array into a string reserved position
(placing char into a string)
注意第 3 点:我们可以推断运行时发生的事情。
在问题中提供的具体示例中 -
printf("%c\n", s); // 3.Outputs "\237". What is this value?
这是处理 UB 时与硬件/编译器/操作系统相关的行为。
为什么?由于输出“\237” -> 这意味着在执行此代码的特定硬件系统下截断!
请看下面的解释(假设——32位系统):
char *s = "12345"; // Declaring a char pointer pointing to a char array
char c = s; // Placement of the pointer into a char - our UB
printf("Pointer to character array: %08x\n", s); // Get the raw bytes
printf("Pointer to character: %08x\n", c); // Get the raw bytes
printf("%c\n", s); // place the pointer as a character
// display is dependent on the ASCII value and the OS
// definitions for 128-255 ASCII values
输出:
Pointer to character array: 004006e4 // Classic 32-bit pointer
Pointer to character: ffffffe4 // Truncation to a signed char
// (Note signed MSB padding to 32 bit display)
� // ASCII value E4 = 228 is not displayed properly
最后的 printf 命令等价于char c = s; printf("%c\n", c);。
为什么?感谢截断。
一个合法的 ASCII 字符输出的附加示例:
char *fixedPointer = 0xABCD61; // Declaring a char pointer pointing to a dummy address
char c = fixedPointer; // Placement of the pointer into a char - our UB
printf("Pointer to 32-bit address: %08x\n", fixedPointer); // Get the raw bytes
printf("Pointer to character: %08x\n", c); // Get the raw bytes
printf("%c\n", fixedPointer);
以及实际输出:
Pointer to 32-bit address: 00abcd61
Pointer to character: 00000061
a