Similar to this question: 2d array, using calloc in C
I need help initializing a 2D char array that will all be initialized to some value (in this case '0'). I have tried many different methods and I am pulling my hair out. Please let me know what I am doing wrong. This code doesn't work. Thanks!
char** init_array() {
char newarray[5][10];
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 10; j++) {
newarray[i][j] = '0';
}
}
return newarray;
}
char **array = init_array();
The errors I get from gcc when I try to compile:
test.c: In function ‘init_array’:
test.c:12:2: warning: return from incompatible pointer type [enabled by default]
return newarray;
^
test.c:12:2: warning: function returns address of local variable [-Wreturn-local-addr]
test.c: At top level:
test.c:14:1: error: initializer element is not constant
char **array = init_array();
Should it be like this?
char newarray[5][10];
char** init_array() {
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 10; j++) {
newarray[i][j] = '0';
}
}
return newarray;
}
char **array = init_array();