为什么它会在数组中不填充的东西?
Why does it cout in something that we doesn't cin in arrays?
当下列程序被输入下列输入时(从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 < 3
和0 <= j < 3
所以你需要将for
循环中的条件改为严格的<
而不是<=
我真的不明白你的问题,但这是错误的:
int arey[3][3];
...
for(j=0;j<=3;j++) // <= invalid
...
array[3][3]=1; // out of bounds
arey
是3*3
数组。你不能访问arey[3][?]
,那是禁区。唯一有效的索引是0..2
。
一旦你写过了数组的边界,你的程序行为就没有定义了。
相关文章:
- C++ 填充数组时遇到问题
- 如何使用同时设置计数和填充数组的函数
- 如何使填充数组的函数发送到函数?而不是其参数中的数组
- 如何使用文件填充数组并将其与用户输入C 进行比较
- 使用 memset 填充数组会显示垃圾
- Visual Studio从文件中填充数组时中断
- 分段 填充数组时出错
- 用不同的值填充数组/矢量的边缘和中心
- 使用相同的数据填充数组对象或使用指针
- 是否可以使用三元运算符"?"在 C/C++ 中填充数组列表?
- 填充数组(写入位置0x00000000的访问冲突)
- 从文件中读取输入并填充数组以存储数据供以后使用
- c++当循环在填充数组时没有正确终止时,希望能帮助退出此循环
- 填充数组会导致数组周围的堆栈损坏
- Cuda有效地将数据插入到未排序的填充数组中
- 填充数组的 C++ 函数
- 访问部分填充数组上的第一个打开元素
- 将一个字节数组从C#传递到C++填充数组的C++com对象中
- 如何使用向量中的信息填充数组并从数组中选择随机项
- C,填充数组使用dec2bin转换器