当我试图调用函数createPlayground时,我得到了一个分段错误,该函数应该在C中打印一个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可以使用其当前签名,因为它不修改指针。

关于c - C Segmentation Fault Print 2D数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55130206/

10-09 13:41