There’s one pointer about the following code I can’t figure out: the part in the function set_array([][9]), why the compiler gives allow this instead the normal full expression set_array([4][9]).However in the main part the int array1[4][9], array1[][9] doesn’t allowed.
#include <stdio.h>
void set_array(int t_array[][9]);
int main(void) {
int array1[4][9]; // array1[][9] doesn't allowed
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 9; j++) {
array1[i][j] = j + 1;
}
}
set_array(array1);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 9; j++) {
printf("%d ", *(*(array1 + i) + j));
//printf("%d ", array1[i][j]);
}
puts("\n");
}
return 0;
}
void set_array(int t_array[][9]) {
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 9; j++) {
t_array[i][j] = 1;
}
}
};
Any explanation about this?
This occurs because when you are doing two different things:
First you are declaring a variable named
array1. In C, the compiler needs to know the amount of space you are declaring to reserve that memory amount to you. So you have to specify the complete size of your array:int array1[4][9];This way your compiler knows that you need
4 * 9ints allocated.Now, in your function the compiler does not need to know the size of your array (behind of scenes your array is converted to a pointer on your function calls), it needs only to know the size of its elements. So
t_arrayis an pointer to elements of size9 * sizeof(int). It is because of that you may declare your function the way you’ve declared:void set_array(int t_array[][9])But it is also possible to declare with all dimension sizes:
void set_array(int t_array[4][9])But it doesn’t matters to the compiler.