关于 C++ 中的二维数组初始化
对于 C++ 中的二维数组初始化这个问题,我得到了不同的答复。
场景如下:
class MyClass {
private:
static char my2dArray[10][20];
};
char MyClass::my2dArray[10][20] = {{0}};
现在是否将此数组的所有元素初始化为 0?
另外,如果我有以下类型定义:
typedef unsigned char u8;
并且此数组是 static u8 my2dArray[10][20],相同的初始化是否有效?
假设所有元素都必须显式初始化为 0。
I get mixed responses for this question on 2-d array initialization in C++.
Here's the scenario:
class MyClass {
private:
static char my2dArray[10][20];
};
char MyClass::my2dArray[10][20] = {{0}};
Now does this initialize all elements of this array with 0?
Also, if I have the following type definition:
typedef unsigned char u8;
and this array is static u8 my2dArray[10][20]
, will the same initialization work?
Assuming it's mandatory that all elements are explicitly initialized to 0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的
如果初始值设定项列表的元素数量与实际数组不同。然后数组被零填充。
是的
同样的流程在这里发挥着作用。
Yes
If the initializer list does not have the same number of elements as the actual array. Then the array is zero filled.
Yes
The same processes is at work here.
有点像。
回想一下,数组的元素不是
char
,而是char[10]
(不能是0
)。您在这里所做的是通过为 first 内部数组 (
{0}
) 提供初始化程序来初始化外部数组,同样仅设置内部数组的 first< /em> 元素到0
)。然后,您将让“默认”隐式初始化行为接管两个数组中的后续元素。
[最终草案] 标准实际上包含类似行为的非规范示例:
所以,最终,是的。所有最里面的数组元素都将保存值
0
;只是您的{{0}}
实际上并没有做太多事情来实现这一点。好吧,由于您的数组具有静态存储持续时间,因此它的内存无论如何都会初始化为零,所以这最终是没有意义的,您不必担心。
是的。类型别名不会改变任何内容:该数组具有与第一个数组完全相同的类型(和存储持续时间),并且适用相同的规则。
Sort of.
Recall that the elements of your array are not
char
, butchar[10]
(which cannot be0
).What you're doing here is initialising the outer array by providing an initialiser for the first inner array (
{0}
, again setting only the inner array's first element to0
).You're then letting the "default", implicit initialization behaviour take over for the subsequent elements in both arrays.
The [final draft] standard actually contains a non-normative example of a similar behaviour:
So, ultimately, yes. All of your innermost array elements will hold the value
0
; it's just that your{{0}}
didn't actually do very much to make that happen.Well, since your array has
static
storage duration, its memory will be zero-initialised anyway, so this is ultimately pointless to bother concerning yourself over.Yes. The type alias doesn't change anything: this array has precisely the same type (and storage duration) as the first one, and the same rules apply.