Why can't I pass a 2D char array in C to a function as
int .....(char array[ ][ ])
i.e with the square brackets empty?
That works with 1D arrays, but I don't understand why it doesn't work with 2d arrays
Why can't I pass a 2D char array in C to a function as
int .....(char array[ ][ ])
i.e with the square brackets empty?
That works with 1D arrays, but I don't understand why it doesn't work with 2d arrays
The reason is that the called function needs to know about the size of the array in order to access the elements.
When you do
int arr[7][5] = {0};
arr[3][2] = 42;
the access is really
*(arr + 3*5 + 2) = 42;
^
note: the number of columns
So in order to access elements in a 2D array the function must have information about the number of columns.
Therefore is
int foo(char array[ ][ ]) { array[3][2] = 42; }
not valid C code. The function simply can't know how to access array[3][2]
But you can do
void foo(char array[][10])
and
void foo(int c, char array[][c])
because in both cases foo
gets the informantion it needs to access the array elements.
You can extend this to arrays of higher dimensions, i.e. the function needs to know the size of all dimensions except the first. Example:
void foo(char array[][42][10])
That works with 1D arrays ? Because in that case in function argument char array[ ]
is not a array
, it's a pointer
. And apart from passing array name
you are passing array size
also to the function, so that you can rotate loop size
times. Here is the simple demo of passing 1D array to function
void pass(int new_arr[],int ele) { /* here new_arr is not an array, it a pointer
*/
/* here this pass() should know how many elements new_arr holds,
that's why second argument is no of element */
}
int main(void) {
int arr[] = {1,2,3,4,5};
int ele = sizeof(arr)/sizeof(arr[0]);
pass(arr,ele);/* you are arr, means 1D array base address and no of elements */
return 0;
}
Why can't I pass a 2D char array in C to a function as int .....(char array[ ][ ])
? Lets look at compiler warning when you tried this
void pass(int new_arr[][],int row) {
}
it says
array type has incomplete element type
So when you pass 2D
array to a function like
int arr[2][3] = { {1,2,3}, {4,5,6}};
pass(arr,row);/* passing 2D array base address to function and you need to inform no of rows to function */
you are just passing 2D
array name i.e base address, how that function will come to know whether you passed 1D
array address or 2D
array address. you(calling function) need to tell to called function that this 2D
array contains this many 1D
array.
So when you are passing 2D
array to a function, called function argument should be of type of pointer to an array like char(*)[row]
not with char**
or char[][]
. for e.g
void pass(int (*new_arr)[3],int row) { /* here new_arr points to 3 elements at a time i.e in each 1D array contains 3 elements*/
}