LeetCode. 54 螺旋矩阵,在判断方向是否需要调转时,为什么定义int类型visit数组在判断条件visit[nextrow][nextcol]处在提交时会产生数组越界的异常,而使用vector定义二维数组visit没有该问题?
报错程序:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
int n = rows * cols;
int visit[rows][cols];
int curderection = 0;
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int row = 0, col = 0;
vector<int> res;
for(int i = 0; i < n; i++){
res.push_back(matrix[row][col]);
visit[row][col] = 1;
int nextrow = row + dir[curderection][0];
int nextcol = col + dir[curderection][1];
if(nextcol < 0 || nextrow < 0 || nextrow >= rows || nextcol >= cols || visit[nextrow][nextcol] ){
curderection = (curderection + 1) % 4;
}
row += dir[curderection][0];
col += dir[curderection][1];
}
return res;
}
通过代码:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
int n = rows * cols;
vector<vector<bool>> visit(rows, vector<bool>(cols)); // 用数组会报越界错误
int curderection = 0;
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int row = 0, col = 0;
vector<int> res;
for(int i = 0; i < n; i++){
res.push_back(matrix[row][col]);
visit[row][col] = 1;
int nextrow = row + dir[curderection][0];
int nextcol = col + dir[curderection][1];
if(nextcol < 0 || nextrow < 0 || nextrow >= rows || nextcol >= cols || visit[nextrow][nextcol] ){
curderection = (curderection + 1) % 4;
}
row += dir[curderection][0];
col += dir[curderection][1];
}
return res;
}
运行结果及报错内容
报错内容:
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x6020000000f0 overflowed to 0x6020000000ec (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
为什么使用vector建立二维数组在临时访问越界处不会报错,而数组临时访问会报错呢?