Home > Blockchain >  How to explain the pointer of array in C?
How to explain the pointer of array in C?

Time:09-09

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 the code of print_array's function can print the information of array? I didn't realized the code,(*p)[i],so i want the master of programmer can help me to work out this qustion.

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.

CodePudding user response:

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 an 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.

CodePudding user response:

p is a pointer to the 10 elements int array.

(*p)[i] first, you dereference the pointer p and you get the array of 10 integers. Then you access the ith element of the array.

CodePudding user response:

array is contagious memory allocation, hence the statement int(*p)[10] = arr;, creating an array of pointers where p[0] is pointing to first element of array.

Now at the function call, *p[i] leads *(p i), i keeps on incrementing hence it will keep on printing the array elements 1st, 2nd, 3rd and so on

  • Related