c - 请解释这个结果。 printf ("%c", 'abcd' )

标签 c memory character-encoding printf

#include <stdio.h>

int main()
{
    printf("%c\n", 'abcd');
    printf("%p\n", 'abcd');
    printf("%c\n", 0x61626364);
    printf("%c\n", 0x61626363);
    printf("%c\n", 0x61626365);
    return 0;
}

我想问这一行:printf("%c\n", 'abcd');
在这一行中,结果是 'd' 但是,我不明白为什么会出现 'd'。
我试图寻找其他内存。在这种情况下,我发现其他内存都是字母。
请解释为什么结果是'd'以及为什么其他内存都是字母。
谢谢。

最佳答案

'abcd' 是一个多字符常量,它的值是实现定义的。

C11 §6.4.4.4 Character constants section 10

An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined. If an integer character constant contains a single character or escape sequence, its value is the one that results when an object with type char whose value is that of the single character or escape sequence is converted to type int.

一个常见的实现给 'abcd' 一个值 'a' * 256 * 256 * 256 + 'b' * 256 * 256 + 'c' * 256 + 'd' (1633837924),您可以通过使用 "%d" 打印它来检查其在您的实现中的值。虽然 C 合法,但在实践中很少使用。

关于c - 请解释这个结果。 printf ("%c", 'abcd' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670059/

相关文章:

C 子文件夹的递归目录副本

c - 使用 makefile 获取编译错误

c - Makefile 对多个文件的依赖

r - 输入矩阵的每一行需要包含至少一个非零项

python - 如何释放 Pandas 数据框使用的内存?

python - 在 Windows 上设置 Python 终端编码

java - 文件编码的默认字符集 - Java

c - 如何在结构中分配内存使其连续

c++ - Directx 11 内存管理

mysql - 如何修复mysql数据编码