首页 > 解决方案 > 检查邻居会给出奇怪的分段错误。C中的生命游戏

问题描述

我正在使用 8192 x 8192 的二维网格制作生命游戏。我通过使用打印语句发现 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;
}

标签: c

解决方案


您的网格大小是8192x8192,但您的数组索引范围是 from08191。因此,当您提供8191for时y,该行会导致分段错误,因为其索引y+1超出8191+1=8192范围。


推荐阅读