In C, if you want a function to create an array and return it to its caller, you must use malloc
or another function that dynamically allocates memory (such as calloc
or realloc
). You can then return a pointer to the array.
char **make2dArray(int x, int y) {
int i;
char **array = calloc(x, sizeof(char*));
for(i = 0; i < x; i++) {
array[i] = calloc(y, sizeof(char));
}
return array;
}
If, on the other hand, you simply need to modify the value of an array, it is best to take the array as a parameter and modify it in place.
void modify2dArray(int x, int y, char **array) {
int i, j;
for(i = 0; i < x; i++) {
for(j = 0; j < y; j++) {
array[i][j] = 1;
}
}
}
And remember, once you're done with dynamically allocated memory, call free for each allocation:
void dealloc2dArray(int x, int y, char **array) {
int i;
for(i = 0; i < x; i++) {
free(array[i]);
}
free(array);
}
Here's what using these functions might look like:
char **array = NULL;
array = make2dArray(5,6);
modify2dArray(5,6,array);
dealloc2dArray(5,6);
array = NULL;
Please note that the dynamic allocation functions (malloc
, calloc
, and realloc
) can fail, returning NULL. I didn't check for NULL after each allocation here to save on space, but it's generally good practice to ensure that your allocations succeed.