Search code examples
cpointersmultidimensional-arrayimplicit-conversionfunction-declaration

How does this function call and definition line up?


I just came across this function call/declaration pair in C, and I'm a bit confused (I'm a newbie here, but I haven't seen this addressed in any of the material I've been using to learn). The function declaration is given as bool read_matrix(double a[][M], int n, int m), but it is called by read_matrix((double (*)[M]) a, n, m). (M is an integer set by #define.) How do these parameters line up with one another? For that matter, what type of object is (*)[M]?

Thanks for clearing up the confusion.


Solution

  • When a function parameter declared with an array type like in this function declaration

    bool read_matrix(double a[][M], int n, int m);
    

    then it is adjusted by the compiler to pointer to the element type.

    So this function declaration is equivalent to the declaration

    bool read_matrix(double ( *a )[M], int n, int m);
    

    On the other hand array designators used in expressions as for example as an argument are converted to pointers to their first elements.

    So if in a caller of the function you have an array declared like

    double a[N][M];
    

    then passed to the function like

    read_matrix( a, N, M );
    

    it is converted to pointer to its first element of the type int ( ^ )[M].

    As for the casting in the call you showed

    read_matrix((double (*)[M]) a, n, m)
    

    then if a is an array declared as shown above then the casting is redundant. This conversion takes place implicitly.