Why does int (* j) [2] = my_array give a warning?

Here is the code:

int my_array[] = {1, 2};
int (*j)[2] = my_array;

The compiler says: "warning: initialization from an incompatible pointer type [enabled by default]"

If I replace the second statement with the following expression, it will compile successfully:

int (*j)[2] = &my_array;

I cannot understand the difference between these two statements because my_array and and my_array store the address of the first element in the array.

+4
source share
3 answers

Always remember the following rule for arrays in C

Array of type Twill be converted to pointer to type Tin most expressions except for &and sizeof.

int my_array[] = {1, 2};
int (*j)[2] = my_array;

my_array pointer to int ( int).

int (*j)[2] = &my_array;

, , , 'my_array', array of int, pointer to int pointer to array of int, LHS

+3

, typedef.

typedef int T[2];

int my_array[] = {1, 2};

T my_array = { 1, 2 };

, T, , ,

T *j = &my_array;

my_array sizeof (T), sizeof( int[2] ), 2 * sizeof( int ) , j T, sizeof( *j ) sizeof (my_array).

T

typedef int T;

int my_array[] = {1, 2};

T my_array[] = {1, 2};

, T, , ,

T *j = my_array;

my_array sizeof (T), sizeof( int ). , j T, sizeof( *j ) sizeof (int).

+2

my_array - int, p - int . , . C my_arry & my_array , .

  • my_array int.

  • & my_array is treated as the address of my_array, it can be assigned to any type of pointer.

0
source

All Articles