簡體   English   中英

C Segmentation Fault Print 2D數組

[英]C Segmentation fault print 2d array

當我嘗試調用函數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可以使用其當前簽名,因為它不會修改指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM