I'm learning about C and pointers in my university class, and I think I've got a pretty good grasp on the concept except for the similarity between multidimensional arrays and pointers.
I thought that since all arrays (even multidimensional) ones are stored in continuous memory, you could safely convert it to a int*
(assuming the given array is an int[]
.) However, my professor said that the number of stars in the definition depends on the number of dimensions in the array. So, an int[]
would become an int*
, a int[][]
would become an int**
, etc.
So I wrote a small program to test this:
void foo(int** ptr)
{
}
void bar(int* ptr)
{
}
int main()
{
int arr[3][4];
foo(arr);
bar(arr);
}
To my surprise, the compiler issued warnings on both function calls.
main.c:22:9: warning: incompatible pointer types passing 'int [3][4]' to parameter of type
'int **' [-Wincompatible-pointer-types]
foo(arr);
^~~
main.c:8:16: note: passing argument to parameter 'ptr' here
void foo(int** ptr)
^
main.c:23:9: warning: incompatible pointer types passing 'int [3][4]' to parameter of type
'int *' [-Wincompatible-pointer-types]
bar(arr);
^~~
main.c:13:15: note: passing argument to parameter 'ptr' here
void bar(int* ptr)
^
2 warnings generated.
What's going on here? How could you change the function calls so one of them would accept the array?
Edit: This is not a duplicate of How to pass a multidimensional array to a function in C and C++ because I'm asking how to change the function calls themselves, not the function signatures.