我正在创建游戏的生命在C和我得到这个分割错误(核心转储)错误后,程序从用户的输入。我最近开始学习C,我对指针的理解是基本的,.I在在线查看并尝试不同的方法使它正确之后,一直未能找到它的修复方法。如果我不使用指针,保持简单,一切正常工作,我将感谢任何帮助。
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发布于 2018-03-13 12:52:10
这里有一个明显的问题。
memcpy(oldGrid, copyGrid,sizeof(oldGrid)); //copy the updated grid to the old one由于oldGrid是一个char**指针,那么sizeof(oldGrid)就是指针的大小,根据平台的不同,指针的大小可能是4或8个字节。所以,您不是在复制网格,而是只复制其中的几个字节。
如果要复制整个网格,则需要以字节为单位计算网格的大小。
如果oldGrid被声明为数组,而不是指针,那么sizeof(oldGrid)将像您所期望的那样生成网格的完整大小。当涉及到sizeof()时,数组的行为与指针不同。
https://stackoverflow.com/questions/49256554
复制相似问题