Search code examples
arrayscfor-looppointersdereference

How can I explain the pointer of an array in C?


Consider:

void print_array(int(*p)[10], int len)
{
    for (int i = 0; i < len; i++)
    {
        printf("%d ", (*p)[i]);
    }
}

int main()
{
    int arr[10] = { 0 };
    int len = sizeof(arr) / sizeof(int);
    for (int i = 0; i < len; i++)
    {
        arr[i] = i;
    }
    int(*p)[10] = arr;

    print_array(p, len);
    return 0;
}

Why can the code of the print_array function print the information of the array?

I didn't realized the code, (*p)[i], so I want the master of programmer can help me to work out this question.

I guess that the reason that I didn't understand this code is that I don't realize the knowledge of the pointer of array.


Solution

  • Let's start from this line

    int(*p)[10] = arr;
    

    The array arr used as an initializer is implicitly converted to a pointer to its first element of the type int *.

    However the initialized pointer p has the type int ( * )[10] and there is no implicit conversion between these two pointers.

    So the compiler should issue at least a warning.

    You have to write

    int(*p)[10] = &arr;
    

    On the other hand, values of the expressions arr and &arr are equal each other. It is the initial address of the extent of memory occupied by the array. (The address of the first element of an array is equal to the address of the array as a whole object).

    So the function accepts a pointer of the type int ( * )[10] that points to an array.

    Dereferencing the pointer in the expression (*p) you get an object of the type int[10] (the array pointed to by the pointer) that is an object of the array type.

    So you can apply the subscript operator (*p)[i] to access elements of the array.