0

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.

Community
  • 1
  • 1
Dovahkiin
  • 946
  • 14
  • 25
  • There is no pointer equivalent for multi-dimensional arrays. Either make the function accept an array of fixed dimensions, or pass a pointer to the first element and then calculate the displacements withing the function yourself. – DYZ Feb 24 '17 at 04:25
  • @DYZ So why do both the above functions give warnings when I attempt to compile the program? – Dovahkiin Feb 24 '17 at 04:27
  • Because you pass a 2D array (an object of one type) instead of pointers (objects of another type). – DYZ Feb 24 '17 at 04:29

1 Answers1

1

Arrays and pointers aren't entirely freely convertible. To not get a warning, you'd need a signature like void foo(int (*ptr)[4]). You can only replace the first [] with a * when passing an array like that to a function.