1

Why the first declaration is valid whereas the other is not ?

    char* string[2] = { "Hello", "Bellow" };

    int* b[2] = { {1,2,3}, {2,3,4} };
yugsharma1711
  • 71
  • 1
  • 9

2 Answers2

1

The reason is that the compiler is not able to imply the type from {1,2,3}, which is desired to be int[3]. You can use array literal to specify it manually as int[3] or int[]:

int *b[2] = { (int[]){1,2,3}, (int[]){2,3,4} };

However, you need to be careful because the lifetime of the literals is bound only to the block where they are defined.

tstanisl
  • 13,520
  • 2
  • 25
  • 40
1

Unless it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted, or "decay", to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array.

In the declaration

char* string[2] = { "Hello", "Bellow" };

the string literals are not being used to initialize a character array, but an array of pointers, so both strings "decay" to pointers to their first element, so you get

char *[2] = { char *, char * };

In the other declaration

int* b[2] = { {1,2,3}, {2,3,4} };

{1,2,3} and {2,3,4} are not array expressions - they’re initializer lists, and they don’t "decay" to pointers. As tstanisl shows, you can use compound literals like

int *b[2] = { (int[]){1,2,3}, (int[]){2,3,4} };

and each of the compound literal expressions will decay to a pointer.

John Bode
  • 119,563
  • 19
  • 122
  • 198