Search code examples
carraysgccpointer-to-array

If int (*p_arr)[10] is defined as a pointer to an array of size 10 then why compiler shows warning in this case?


I have this code:

#include <stdio.h>

int main()
{
    int arr[10] = {0};
    int *p1_arr = arr;
    int (*p2_arr)[10] = arr;      // Line 7, Shows Warning here

    ...

    return 0;
}

On compiling on gcc using gcc -g -Wall LengthofArray.c, it shows following warning:

gcc: LengthOfArray.c:7: [Warning] assignment from incompatible 
                         pointer type [enabled by default]

My question is if int (*p2_arr)[10] is a pointer to an array of size 10, then why compiler shows this warning?

Also what is the correct way then?

I used gcc 4.7.2 on Windows 7 32-bit (DevC++)
and also checked on gcc 4.1.2 on SLES 10.3 x86_64


Solution

  • ... if int (*p2_arr)[10] is a pointer to an array of size 10 ...

    As p2_arr points to an array of size 10, you need to assign an address of an array of size 10:

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