我一直在四处阅读,我一直在将我一直在阅读的内容应用到我的代码中,但我不确定我是否遗漏了什么。二维数组应该是数独的镜像。
我知道问题区域在我的 arrayMake 函数中。
我的教授建议在 malloc 调用中使用强制转换,因此:
sudoku = (int**)malloc(sudokus*sizeof(int*));
但这对我不起作用。
int main(){
int sudokus;
int** sudoku;
sudokus = getUserInfo();
sudoku = arrayMake(sudokus);
/*for (int i = 0; i < (SIZE*sudokus), i++;){
for (int j = 0; j < SIZE, j++;){
printf("Numbers[%d][%d]:%d", i, j, sudoku[i][j]);
}
}*/
system("pause");
return 0;
}
int getUserInfo(){
int sudokus;
printf("How many Sudokus are you checking today?\n");
scanf("%d{^\n]\n", &sudokus);
return sudokus;
}
int** arrayMake(int sudokus){
int **sudoku;
int realsize;
realsize = 9 * sudokus;
sudoku = malloc(realsize*sizeof(int*));
if (sudoku == NULL){
printf("Memory allocation failed");
return 0;
}
for (int i = 0; i < realsize, i++;){
sudoku[i] = malloc(9 * sizeof(int));
if (sudoku[i] == NULL){
printf("Memory allocaiton failed");
return 0;
}
}
return sudoku;
}
最佳答案
My professor recommended using a cast with the malloc call so: sudoku = (int**)malloc(sudokus * sizeof(int*)); but that did not work for me.
动态分配二维数组,通常需要做两步。您的代码不清楚,因为您包含一个没有意义的 realsize = 9 * sudokus
。无论如何,为简单起见,我们假设您的数独是一个 3x3 矩阵。你需要:
分配指向 int 的指针:
int **sudoku = malloc( 3 * sizeof( int * ) );
为每个指向 int 的单独指针分配:
for( int i = 0; i < 3; i++ ) sudoku[i] = malloc( 3 * sizeof( int ) );
关于c - 在 C 中动态分配二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983352/