gpt4 book ai didi

c - sizeof (""+0) != sizeof(char *) 错误或未定义的行为?

转载 作者:太空狗 更新时间:2023-10-29 16:34:21 24 4
gpt4 key购买 nike

下面的 C 程序:

#include <stdio.h>

int main(void)
{
printf("%u %u %u\n",sizeof "",sizeof(""+0),sizeof(char *));
return 0;
}

在 Linux 上使用 GCC 编译时输出 1 4 4,但在 Windows 上使用 Microsoft Visual C++ 编译时输出 1 1 4。 GCC 结果是我所期望的。它们不同是因为 MSVC 有错误还是因为 sizeof(""+0) 未定义?对于这两种编译器,无论您使用什么字符串文字或整数常量,行为(即打印的中间值等于第一个值还是最后一个值)都是相同的。

ANSI C 标准中的相关引用似乎是 6.2.2.1 - Lvalues and function designators:

Except when it is the operand of the sizeof operator ... an lvalue that has type 'array of type' is converted to an expression that has type 'pointer to type' that points to the initial element of the array object and is not an lvalue.

这里虽然“Except”不应该适用,因为在 sizeof(""+0) 中,数组/字符串文字是 + 的操作数,而不是 sizeof

最佳答案

因为 "fooabc"char[7] 类型,sizeof("fooabc") 产生与 sizeof 相同的结果(字符[7])。但是,数组可以隐式转换 - 你引用的部分 - 指针(有些人错误地称之为“衰减”),因为这是算术 (+) 工作所必需的, ""+0 将具有 char* 类型。并且 char 指针可以具有与数组不同的大小。在这方面,MSVC 的行为似乎有问题。

关于c - sizeof (""+0) != sizeof(char *) 错误或未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4862522/

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