c - 检查邻居会给出奇怪的分段错误。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
,但您的数组索引范围是 from0
到8191
。因此,当您提供8191
for时y
,该行会导致分段错误,因为其索引y+1
超出8191+1=8192
范围。
推荐阅读
- javascript - 如何获得在用户同意期间授予范围的用户的子用户?
- matlab - OpenGL:沿 z 坐标平移纹理不会产生任何效果
- node.js - Angular - 创建一个需要 2 个日期和一周中的一天的函数,并创建一周中同一天的日期数组
- python - ValueError:轴与数组不匹配 - 无法转置数组
- ruby-on-rails - Rails 用 odoo 设计了omnioauth
- python - seaborn中小提琴图的透明面
- ios - iPadOS 15 beta 中带有 UIKeyCommand 的键盘快捷键
- python - 使用 python web 抓取代码完成增量表刷新
- python - pandas 图形上不需要的级别和错误的计算
- apache-spark-sql - 如何在 spark-sql 中从 UDF 中删除空行?