数组为什么打印垃圾值?
我创建了一个2D数组,并在C ++中初始化为0。
int n;
cin>>n;
int ar[n][n]={0};
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<ar[i][j]<<" ";
}
cout<<endl;
}
当我打印此数组时,它将在第一行中打印随机垃圾值,如下所示,
0 0 4294220 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
为什么会发生这种情况。我已经阅读了有关可变长度阵列在这里 。但是我找不到任何解释,为什么会发生这种情况。
I have created a 2d array and initialized to 0 in C++.
int n;
cin>>n;
int ar[n][n]={0};
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<ar[i][j]<<" ";
}
cout<<endl;
}
When I print this array, it prints random garbage values in the first row as shown below
0 0 4294220 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Why is this happening. I have read about variable length arrays here. But I can't find any explanation why is this happening.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您声明了一个可变长度数组,
但是可变长度阵列不是标准的C ++功能。可变长度阵列有条件地由C编译器支持。
但是,您可能不会在声明中初始化可变长度数组。
设置为零元素元素的一种简单方法是使用C标准函数
memset
。例如,您可以使用标准算法
std :: fill
在标题&lt; algorithm&gt;
中声明,例如在基于范围的循环中。否则,您可以使用标准容器
std :: vector&lt; std :: vector&lt; int&gt;&gt;
。例如
,在这种情况下,声明之后的所有元素将被零界化。
You declared a variable length array
However variable length arrays are not a standard C++ feature. Variable length arrays are conditionally supported by C compilers.
Nevertheless you may not initialize a variable length array in its declaration.
A simple way to set to zero elements of the array is to use the C standard function
memset
. For exampleOr you could use the standard algorithm
std::fill
declared in the header<algorithm>
for example in a range-based-for loop.Otherwise you can use the standard container
std::vector<std::vector<int>>
.For example
In this case all elements after the declaration will be zero-initialized.