c - 可变长度数组上 sizeof 的行为(仅限 C)

标签 c sizeof

我的问题是,当传递的参数是一个动态数组 可变长度数组时,sizeof() 的行为如何。

让我们考虑一个例子:

int fun(int num_of_chars)
{
    char name_arr[num_of_chars] = {0};

    /* Do something*/

    return sizeof(name_arr);
}

在这个例子中很明显返回值不是编译时常量。因为大小取决于 num_of_chars 的运行时值。

引自 C99 标准 (6.5.3.4):

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

我从 [....the operand is evaluated....] 中可以理解的是,当传递给 sizeof() 的参数是一个动态数组可变长度数组,sizeof()“表现得像”函数而不是运算符

我的理解对吗?

最佳答案

它仍然像一个运算符(operator)一样工作。 Cast 也是运算符,也评估它的参数, *& 也是如此。作为运算符是一个句法范畴。这不会改变。

重要的区别在于它表现为表达式,而在其他情况下它表现为常量


更新:我在下面评论说我不明白为什么评估会有所不同,但现在我意识到有两种方法可以用可变长度数组编写 sizeof。您可以传递声明为可变长度数组的变量:

int a[x];
sizeof(a)

在这种情况下评估 a 确实没有区别。但您也可以使用类型 作为参数,即

sizeof(int[x])

在这种情况下,结果是 x * sizeof(int) 并且必须评估 x。我想这就是规范提到它的原因。

关于c - 可变长度数组上 sizeof 的行为(仅限 C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14995870/

相关文章:

c - 编译C程序时gcc的错误

c - 作为 sizeof 操作数的结构名称

无法通过 execlp 执行二进制文件

c - c程序输出中的sizeof

c++ - sizeof(值)与 sizeof(类型)?

c - 标准 C 中的 sizeof 与 sizeof()?

c - 数据处理代码中的段错误

c++ - 在 Cocoa 应用程序中使用大型 C++ 库的推荐方法?

c - 为什么标准禁止将 sizeof 应用于函数

c - 为什么重新定义 sizeof 有效