当我尝试调用函数createPlayground
时,该函数应在Console中打印一个2D数组,我会得到分割故障。我不知道怎么了。
#include<stdio.h>
#include<stdlib.h>
void createPlayground(int, int **);
void printPlayground(int, int **);
int main() {
int size = 8;
int **playground;
createPlayground(size, playground);
printPlayground(size, playground);
return 0;
}
void createPlayground(int size, int **array) {
array = (int **) malloc(size * sizeof(int *));
for (int i = 0; i < size; ++i) {
array[i] = (int *) calloc(size, sizeof(int));
}
}
void printPlayground(int size, int **array) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j){
printf("%d ", array[i][j]);
}
printf("n");
}
}
您需要将另一个间接级别添加到createPlayground
:
void createPlayground(int size, int ***array) {
*array = (int **)malloc(size * sizeof(int *));
for (int i = 0; i < size; ++i) {
(*array)[i] = (int *)calloc(size, sizeof(int));
}
}
这样称呼:
createPlayground(size, &playground);
请注意,printPlayground
的当前签名很好,因为它没有修改指针。