gpt4 book ai didi

c - 海湾合作委员会 fprintf : should that be an int (32bit) or char (8bit)?

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:08 24 4
gpt4 key购买 nike

哪些代码有效?我在输出中得到零个字符,想知道这是否是由于将字符作为整数处理不当造成的,反之亦然。 %c 说明符是应该打印的内容,我只是不确定最后一个参数。

int c;
fprintf(stdout, "%c", c);
int n;
fprintf(stdout, "%c", n);

关于 scanf 的相同问题,应该是 char 还是 int 还是两者之一?

最佳答案

两者都可以。 ISO C11 标准在 7.21.6.1 The fprintf function /9 中声明(所有各种 *printf*scanf 调用都是根据 fprintffscanf 定义的):

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

但是,在 %c ( /8 ) 部分中,它还指出(我的重点):

If no l length modifier is present, the int argument is converted to an unsigned char, and the resulting character is written.

事实上,传递 intchar 没有区别,因为默认参数提升是在省略号之外的可变参数类型函数上执行的(根据 6.5.2.2 Function calls /6/76.3 Conversions )

... the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.

The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

因此,由于 fprintf 是这样定义的:

int fprintf(FILE * restrict stream, const char * restrict format, ...);

这意味着 char 参数无论如何都会升级为 int


fscanf 是另一回事。它在 7.21.6.2 The fscanf function /12 中声明(再次强调,我的重点):

If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence. No null character is added.

这意味着您应该提供一个字符(或字符数组)的地址。如果您提供的 int 大小不同,您可能只会看到该 int部分发生了变化,其余部分将保留为某个任意值。例如,在八位字节、四字节 int 大端系统上:

+------+------+------+------+
| 0x12 | 0x34 | 0x56 | 0x78 | <- Initial value of int 0x12345678
+------+------+------+------+
| 0x36 | .... | .... | .... | <- Read character '6' (0x36 in ASCII)
+------+------+------+------+
| 0x36 | 0x34 | 0x56 | 0x78 | <- Final value of int 0x36345678
+------+------+------+------+

您可以看到 int其他字节保持不变(由 .... 表示),导致 int 的最终值是 0x36 之外的其他值。

关于c - 海湾合作委员会 fprintf : should that be an int (32bit) or char (8bit)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51073550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com