When I try to call the function createPlayground
, which should print a 2D array in C to the console I get a Segmentation fault. 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
:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.