这段代码是否真的检查了数组的界限?
在这种情况下,限制在2d阵列中为0 - 20
int noOfNeighbors(game *g, int row, int column){
int aliveCounter = 0;
for(int rows=-1; rows<=1; rows++) {
for(int cols=-1; cols<=1; cols++) {
if((rows || cols)) {
if(row+rows < (*g).rows && row+rows >= 0){
if(column+cols < (*g).columns && column+cols >= 0){
if(isAlive(g,row+rows,column+cols)){
aliveCounter++;
}
}
}
}
} //end cols
}//end rows
return aliveCounter;
}//end noOfNeighbors
其中
typedef struct {
char current;
char next;
} cell;
typedef struct {
cell field[MAX_ROWS][MAX_COLUMNS];
int rows;
int columns;
char aliveChar;
char deadChar;
} game;
并且行和列设置为20
更新了代码,现在检查0-19
答案 0 :(得分:2)
这段代码是否真的检查了数组的界限?
是即可。你能告诉我们你不明白的东西吗?我们可以更具体一点吗?
另外,你可以改变:
(*g).rows
到
g->rows
它更容易阅读。
编辑:我刚刚注意到问题中的代码已经过编辑和修复。所以我猜你自己发现了问题:在最初的问题中,比较中存在问题(<=
而不是<
)。
答案 1 :(得分:0)
这不是答案,但评论时间太长了:
您提交的代码 有很多问题:我只会解决这些问题:
正如其他人在评论和其他答案中已经注意到的那样:使用g-&gt;行而不是(* g).rows
在代码部分 :
int noOfNeighbors(game *g, int row, int column){
int aliveCounter = 0;
for(int rows=-1; rows<=1; rows++) {
for(int cols=-1; cols<=1; cols++) {
if((rows || cols)) {
if(row+rows < (*g).rows && row+rows >= 0){
编写方式时,最后一行的结果是不确定的。也就是说,内部循环,第一个达到1是cols(行仍然是-1),而在比较(*g).rows && row+rows >= 0)
`(* g).rows尚未初始化。
然后,在以下行中:
if(column+cols < (*g).columns && column+cols >= 0){
出于同样的原因会产生不确定的结果。
根据所呈现的内容,无法确定执行流程何时最终会进入循环的核心:
if(isAlive(g,row+rows,column+cols)){
aliveCounter++;
}
首先建议您提供符合 SSCCE 的代码段,并可能解释确切的意图是什么,以及它在哪里落下没有期望。