简体   繁体   English

C Segmentation Fault Print 2D数组

[英]C Segmentation fault print 2d array

When I try to call the function createPlayground , which should print a 2D array in C to the console I get a Segmentation fault. 当我尝试调用函数createPlayground ,该函数应该在C中将2D数组打印到控制台,但出现分段错误。 I don't know what is wrong. 我不知道怎么了

#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");
    }
}

You need to add another level of indirection to createPlayground : 您需要向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));
    }
}

Call it like so: 这样称呼它:

createPlayground(size, &playground);

Note that printPlayground is fine with its current signature since it doesn't modify the pointers. 请注意, printPlayground可以使用其当前签名,因为它不会修改指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM