【发布时间】:2018-03-13 12:43:52
【问题描述】:
我正在用 C 语言创建生命游戏,在程序接受用户输入后,我收到了这个分段错误(核心转储)错误。我最近开始学习 C 并且我对指针的理解是基本的。在网上查找并尝试不同的方法使其正确后,我无法找到解决它的方法。如果我不使用指针并保持简单,一切正常。我将不胜感激
int main() {
int maxR;
int maxC;
int generations;
int i=0;
int j=0;
int k=0;
int n; //neighbour count
char state;
char **board; //original boardfor comparison
char **newBoard; //boardto make changes to
scanf("%d %d %d",&maxR,&maxC,&generations); //take input
board= (char**)malloc(maxR * sizeof(char*)); //allocating memory
newBoard=(char**) malloc(maxR * sizeof(char*)); //allocating memory
for(i=0; i<maxR; i++) {
board[i] = malloc(maxC * sizeof (char)); //allocating memory
newBoard[i] = malloc(maxC * sizeof (char)); //allocating memory
for(j=0; j<maxC; j++) {
scanf (" %c", &board[i][j]); //getting input
}
}
for(i=0; i<=generations; i++ ) {
for (j=0; j<maxR; j++) {
for (k=0; k<maxC; k++) {
state=board[j][k];
n=countNeighbours(board,maxR,maxC,j,k);
if(state == '1') { //if the cell is alive
if(n==2 || n==3) newBoard[j][k] = '1'; //if the cell has 2 or 3 neighbours then it lives
else newBoard[j][k]='0'; //else the cell dies
} else { //else (if) the cell is dead
if(n==3) newBoard[j][k]='1'; //but has 3 neibours then the cell become alive
else newBoard[i][j]='0'; //else it dies
}
}
}
memcpy(board, newBoard,sizeof(board)); //copy the updated grid to the old one
}
printBoard(board,maxR,maxC);
deallocate(board,maxR); //deallocatethe memory
deallocate(copyGrid,maxR); //deallocatethe memory
【问题讨论】:
标签: c pointers multidimensional-array