簡體   English   中英

檢查鄰居給出了奇怪的分段錯誤。 C中的生命游戲

[英]Check neighbors gives weird segmentation fault. Game of Life in 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;
}

您的網格大小為8192x8192但您的數組索引范圍為08191 因此,當您為y提供8191時,該行會導致分段錯誤,因為y+1的索引8191+1=8192超出范圍。

我的 if 語句錯誤非常簡單,只需在確保您不在邊界時從 GRIDSIZE 中減去 1。

if (y < GRIDSIZE) neighbours = neighbours + grid[y + 1][x] == 1;

if (y < GRIDSIZE - 1) neighbours = neighbours + grid[y + 1][x] == 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM