为什么这个 'sizeof()' return 在 C 中是 0 字节?

Why this 'sizeof()' return is 0 bytes in C?

我的问题是关于 sizeof 和内存分配。当我学习 C 和测试类型值时,我尝试了这段代码:

#include <stdio.h>

int main(void) {
char vec[0];
vec[0] = 1;
printf("\n SIZEOF: %li", sizeof(vec));
printf("\n VEC[0]: %li", vec[0]);
}

输出是:

> SIZEOF: 0

> VEC[0]: 1

为什么即使我添加值“vec[0] = 1”,“vec[0]”的大小也是“0 字节”? (如果我不添加这个值,只需声明向量“char vec[0] 或 int vec[0]”,输出是相同的)。

Rickxk。时间不多了。

vec 被定义为一个大小为零元素的数组。零元素的大小为零,这似乎是明智的。给 vec[0] 赋值会覆盖某处的内存。

数组必须定义为正数。

您创建了一个大小为 0 的代码,这违反了约束,因此您的代码显示 undefined behavior

这段代码

char vec[0];
vec[0] = 1;

调用未定义的行为。

您不能声明包含零个元素的数组。

来自 C 标准(6.7.6.2 数组声明符)

1 In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or *. If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero. The element type shall not be an incomplete or function type. The optional type qualifiers and the keyword static shall appear only in a declaration of a function parameter with an array type, and then only in the outermost array type derivation.

注意在这些printf调用中使用了不正确的转换说明符

printf("\n SIZEOF: %li", sizeof(vec));
printf("\n VEC[0]: %li", vec[0]);

对于运算符 sizeof 返回的具有类型 size_t 的值,您应该使用转换说明符 %zu,对于类型为 char 的对象,您应该使用转换说明符 %c.

关于你的问题

Why "vec[0]" has a size of "0 bytes" even I adding value "vec[0] = 1" ? (If I don't add this value, just declare the vector "char vec[0] or int vec[0]" the output is same).

那么编译器应该发出一条关于无效数组声明的消息。

至于输出,因为数组不是可变长度数组,所以表达式 sizeof( vec ) 的值在编译时求值。编译器看到元素的数量等于 0,并将表达式 sizeof( vec ) 计算为 0 * sizeof( char )。因此,此表达式总是产生 0 独立于数组元素类型。

当您写 vec[0] = 1;.

时,您实际上并不是在填充长度为 0 vec 的“数组”中的位置

请记住,当您声明一个长度为 N 的数组时,其有效索引为 0, 1, 2 ... N-1。如果数组的大小为 0,则有效索引是什么? None 个!

这是同一种未定义行为:

int data[3] = { 1, 2, 3 };
data[10000] = 10;

它可能在您的系统上写入 vec[0],但它仍然不是属于 vec 的内存。