[英]C initialized and non initialized array with variable size
I have the next two code examples:我有接下来的两个代码示例:
const char *val = strchr(ch, ' ');
const int diff = (int)(val - ch);
char arr[diff];
and和
const char *val = strchr(ch, ' ');
const int diff = (int)(val - ch);
char arr[diff] = {0};
The second one generates the error like第二个产生错误,如
error: variable-sized object may not be initialized
错误:可变大小的 object 可能未初始化
It is correct error and I understand why it happens.这是正确的错误,我理解它为什么会发生。
I wonder why the first code snippet doesn't generate the error?我想知道为什么第一个代码片段不会产生错误?
Update: Also regarding sizeof(arr) at first snippet gives the size of array, but I thought that sizeof is a compile time operator (?)更新:关于 sizeof(arr) 的第一个片段也给出了数组的大小,但我认为 sizeof 是一个编译时运算符(?)
In the second case you are trying to initialize a variable length array (because the size of the array is not specified with an integer constant expression; the presence of the qualifier const
in the declaration of the variable diff does not make it an integer constant expression in the array declaration)在第二种情况下,您尝试初始化一个可变长度数组(因为数组的大小不是用 integer 常量表达式指定的;变量 diff 的声明中存在限定符
const
不会使其成为 integer 常量表达式在数组声明中)
char arr[diff] = {0};
that is not allowed for variable length arrays.这对于可变长度 arrays 是不允许的。
From the C Standard (6.7.9 Initialization)来自 C 标准(6.7.9 初始化)
3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type
3 待初始化实体的类型应该是一个未知大小的数组或者一个完整的object类型不是变长数组类型
You could set all elements of the array to zero the following way您可以通过以下方式将数组的所有元素设置为零
#include <string.h>
//...
char arr[diff];
memset( arr, 0, diff );
As for the operator sizeof
then for variable length arrays it is calculated at run-time.至于运算符
sizeof
那么对于可变长度 arrays 它是在运行时计算的。
From the C Standard (6.5.3.4 The sizeof and alignof operators)来自 C 标准(6.5.3.4 sizeof 和 alignof 运算符)
2 The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type.
2 sizeof 运算符产生其操作数的大小(以字节为单位),它可以是表达式或类型的括号名称。 The size is determined from the type of the operand.
大小由操作数的类型决定。 The result is an integer.
结果是 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
否则,不计算操作数,结果为 integer 常量
This definition:这个定义:
char arr[diff];
Creates a variable length array .创建一个可变长度数组。 Such an array has its size determined at runtime.
这样的数组的大小在运行时确定。 Because of this, it may not be initialized.
因此,它可能未初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.