我正在制作一个二维网格为8192x8192的生活游戏。通过使用Print语句,我发现当getNeighbours()被赋予y=8191和x=1000时,它会导致分段错误。
#include <stdio.h>
const int GRIDSIZE = 8192;
int grid[8192][8192];
// counts the amount of live neighbours to y, x
int getNeighbours(int y, int x){
int neighbours = 0;
// if not at top check up
if (y > 0) neighbours = neighbours + grid[y - 1][x] == 1;
// if not at bottom check below
if (y < GRIDSIZE) neighbours = neighbours + grid[y + 1][x] == 1; // This will cause segmentation fault at y 8191 x 1000
if (y == GRIDSIZE - 1) printf("%d, %d\n", y, x);
// if not at leftmost check left
if (x > 0) neighbours = neighbours + grid[y][x - 1] == 1;
// if not at rightmost check right
if (x < GRIDSIZE) neighbours = neighbours + grid[y][x+1] == 1;
return neighbours;
}发布于 2020-10-28 02:42:09
你的网格大小是8192x8192,但是你的数组索引范围是从0到8191。因此,当您为y提供8191时,该行会导致分段错误,因为y+1的索引8191+1=8192超出范围。
发布于 2020-10-28 02:44:23
我的if语句是错误的,非常简单,当你确定你不在边界时,从GRIDSIZE中减去1即可。
在此之前
if (y < GRIDSIZE) neighbours = neighbours + grid[y + 1][x] == 1;之后
if (y < GRIDSIZE - 1) neighbours = neighbours + grid[y + 1][x] == 1;https://stackoverflow.com/questions/64560932
复制相似问题