Search code examples
cpointersmultidimensional-arrayimplicit-conversionfunction-parameter

What is int (*tabes)[N]?


1 Question - What the pointer does in this code 2 Question - Why is the argument of a function a one-dimensial array when we pass a two-dimensial array

#define N 10
int tab[N][N]

void create(int (*tabes)[N]){
     for (i=0; i<N; i++){
       for (j=0; j<N; j++){
          tabes[i][j] = 2;
       }
    }
}

int main(){
    create(tab);
}

Solution

  • Dynamic array allocation with pointer only

    For starters there is no dynamic array allocation in the presented code in your question. So the title of the question is confusing.

    This declaration of an array where you forgot to place a semicolon

    int tab[N][N]
    

    declares an array with static storage duration.

    After you changed the title to

    What is int (*tabes)[N]?

    then shortly speaking it is a declaration of a pointer with the name tabes that points to an object of the array type int[N].

    2 Question - Why is the argument of a function a one-dimensial array when we pass a two-dimensial array

    I think you wanted to say why the parameter of the function is a one-dimensional array because it is clear that the argument of the function call

    create(tab);
    

    is a two-dimensional array.

    Well you could declare the function like

    void create(int tabes[][N]){
        //...
    }
    

    As you see the parameter has a two-dimensional array. But the compiler adjusts the parameter to pointer to the array element type. The element type of the array tab declared like

    int tab[N][N];
    

    is int[N]. So the pointer type to the element of the array will look like int ( * )[N]. This type is used in your function declaration.

    That is these function declarations

    void create(int tabes[N][N]);
    void create(int tabes[][N]);
    void create(int ( *tabes )[N]);
    

    declare the same one function because as it was said a parameter having an array type is adjusted by the compiler to the parameter having a pointer type to the array element type.

    So the function deals with a pointer to an array of the type int[N].

    On the other hand, the array tab used as an argument of the function call is implicitly converted to a pointer to its first element. Again this pointer has the type int ( * )[N].

    In fact this call

    create(tab);
    

    is equivalent to the following call

    int ( *ptr )[N] = tab;
    create( ptr );
    

    except that in the last case there is used an auxiliary variable ptr.