为什么它会在数组中不填充的东西?

Why does it cout in something that we doesn't cin in arrays?

本文关键字:填充 数组 为什么      更新时间:2023-10-16

当下列程序被输入下列输入时(从cin读取):

1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1

输出令人惊讶:

1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1
#include<iostream>
using namespace std;
int main()
{
    int arey[3][3];
    int i,j;
    for(j=0;j<=3;j++)
    {
        for(i=0;i<=3;i++)
        {
            cin>>arey[j][i];
        }
    }
    arey[0][0]=1;
    arey[3][3]=1;
    i=0,j=0;
    for(j=0;j<=3;j++)
    {
        for(i=0;i<=3;i++)
        {
            cout<<arey[j][i];
        }
    }
    return 0;
}

有人能解释一下我应该改变什么才能得到与输入相同的输出吗?

矩阵是3x3还是4x4?

你创建了3x3,但是循环运行了4个元素,你也更新了[3][3]

基本上你的索引溢出,你在矩阵中覆盖一个不同的单元格。

更新:检查您的输入,使用:int arey[4][4];

数组使用基于0的索引,因此

的有效索引范围

int arey[3][3];

分别为0 <= i < 30 <= j < 3

所以你需要将for循环中的条件改为严格的<而不是<=

我真的不明白你的问题,但这是错误的:

int arey[3][3];
...
for(j=0;j<=3;j++) // <= invalid
...
array[3][3]=1;    // out of bounds

arey3*3数组。你不能访问arey[3][?],那是禁区。唯一有效的索引是0..2

一旦你写过了数组的边界,你的程序行为就没有定义了。