尝试在循环中访问数组元素会导致分段错误,为什么? [英] Trying to access array element in loop causes segmentation fault, why?
问题描述
我正在尝试创建一个二维数组,该数组将1或0随机分配给每个坐标.直到到达坐标[20] [3]为止,它都可以正常工作.之后,它仅抛出分段错误11".
我绝对不知道如何或为什么.尤其是因为我可以创建一个200 * 200的矩阵,但它仍然仅在坐标[200] [3]时出现相同的问题.因此,总是会在最后一个x坐标中的第三个y坐标发生错误.
#include <stdio.h>
#include <stdlib.h>
int main() {
int x, y, i, j ;
x = 20;
y = 20;
int grid [x][y];
for ( i = 0; i <= x; i++) {
for ( j = 0; j <= y; j++) {
grid[i][j] = rand() % 2 ;
printf("grid [%d][%d]: %d\n", i, j, grid[i][j]);
}
}
return 0;
}
C对数组使用基于0的索引.因此,对于定义为
的数组int grid [x][y]
循环
for ( i = 0; i <= x; i++)
for ( j = 0; j <= y; j++)
如果一对一. (请注意<=
部分).
p
的数组,有效索引为0
至p-1
(含).
您应该将循环条件更改为i < x
和j < y
以保持界限.访问超出范围的内存会导致未定义的行为.
说,
-
int main()
至少应为int main(void)
,以符合托管环境的C标准. - 此处无需将
grid
设置为VLA.如果尺寸已知,更好的方法是使用编译时常量(#define
)生成数组尺寸.
I am trying to create a two dimensional array, which has either 1 or 0 randomly assigned to each coordinate. It works just fine until it gets to the coordinates [20][3]. After that it just throws out "segmentation fault 11".
I am absolutely clueless how or why. Especially since I can create a matrix with 200 * 200 for instance but it still gets the same Problem only at the coordinates [200][3]. So it is somehow always the third y coordinate in the last x coordinate where the error occurs.
#include <stdio.h>
#include <stdlib.h>
int main() {
int x, y, i, j ;
x = 20;
y = 20;
int grid [x][y];
for ( i = 0; i <= x; i++) {
for ( j = 0; j <= y; j++) {
grid[i][j] = rand() % 2 ;
printf("grid [%d][%d]: %d\n", i, j, grid[i][j]);
}
}
return 0;
}
C uses 0-based indexing for arrays. So, for an array defined as
int grid [x][y]
looping for
for ( i = 0; i <= x; i++)
for ( j = 0; j <= y; j++)
if off-by-one. (Note the <=
part).
to elaborate, for an array of dimension p
, the valid indexes are 0
to p-1
, inclusive.
You should change your loop conditions as i < x
and j < y
to stay withing the bounds. Accessing out of bound memory causes undefined behavior.
That said,
int main()
should beint main(void)
, at least, to conform to C standards for hosted environments.- There is no need to make
grid
as VLA here. If the dimensions are already known, better approach is to use a compile-time constant (#define
) to generate the array dimensions.
这篇关于尝试在循环中访问数组元素会导致分段错误,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!