数组为什么打印垃圾值?

发布于 2025-02-01 05:04:19 字数 579 浏览 1 评论 0原文

我创建了一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小瓶盖 2025-02-08 05:04:19

您声明了一个可变长度数组,

int n;
cin>>n;
int ar[n][n]={0};

但是可变长度阵列不是标准的C ++功能。可变长度阵列有条件地由C编译器支持。

但是,您可能不会在声明中初始化可变长度数组。

设置为零元素元素的一种简单方法是使用C标准函数memset。例如

#include <cstring>

//...

memset( ar, 0, n * n * sizeof( int ) );

,您可以使用标准算法std :: fill在标题&lt; algorithm&gt;中声明,例如在基于范围的循环中。

否则,您可以使用标准容器std :: vector&lt; std :: vector&lt; int&gt;&gt;

例如

std::vector<std::vector<int>> ar( n, std::vector<int>( n ) );

,在这种情况下,声明之后的所有元素将被零界化。

You declared a variable length array

int n;
cin>>n;
int ar[n][n]={0};

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 example

#include <cstring>

//...

memset( ar, 0, n * n * sizeof( int ) );

Or 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

std::vector<std::vector<int>> ar( n, std::vector<int>( n ) );

In this case all elements after the declaration will be zero-initialized.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文