我的数组的大小为3x3,这意味着我的索引值仅为0到2。 但是当我使用for循环遍历时,为什么它要在[2][0]的值上拾取[3][-3]的值???
当我尝试[3][3]时,错误是什么,它应该给出垃圾值,为什么会出现这个错误
***检测到堆栈崩溃***:已终止
#include <bits/stdc++.h>
#include <iostream>
#define vi vector<int>
using namespace std;
int main()
{
char a[3][3];
int pos, row, col;
cin >> pos;
memset(a, 48, sizeof(a));
//row = pos / 3;
//col = pos % 3 - 1;
a[3][3] = 'X';
//a[3][-3] = 'X';
for (char *b : a)
{
for (size_t i = 0; i < 3; i++)
{
cout << b[i] << " ";
}
cout << endl;
}
}
对于[3][-3]结果将输出:
0 0 0
0 0 0
X 0 0
对于[3][3],将输出结果:
0 0 0
0 0 0
0 0 0
*** stack smashing detected ***: terminated
Aborted (core dumped)
对于像A[3][3]
这样的数组,用[3][3]
或[3][-3]
索引到A
会调用未定义的行为。 任何事情都可能发生,包括打印出垃圾值。 程序甚至不能保证打印一个值,它可能会崩溃。
两个绑定的唯一有效索引是0
,1
和2
。
请注意,即使您正确地索引到a
中,从a
中读取也是未定义的行为,因为您还没有初始化a
。 你可以这样做:
char a[3][3]{};
现在从a[2][0]
读取就可以了。
这是因为错误的算术,正如@Kevin在评论中所回答的那样
A[2][0]=2*3+0=6
字节
而且还
A[3][-3]=3*3-3=6
字节
所以两者都指向相同的值。