gcc compile error: cast specifies array type

This is valid because the expression on the right hand side is a C99 compound literal, not a cast:

int *ia = (int[]){1,3,5,7};    /* Valid */

However, this is not valid because it is a cast-expression, not a compound literal. As GCC is telling you, you can't cast to array types:

char *p = (char[]) "abc";     /* NOT Valid */

You can fix it by making it a proper compound literal - they are denoted by the braces:

char *p = (char[]){"abc"};    /* Valid */

C11 6.5.2.5p3:

  1. A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

(emphasis mine).

I.e., type in parentheses (char []), followed by brace-enclosed list of initializers, { 'a', 'b', 'c', '\0' }.

Since paragraph 6. says that

  1. All the semantic rules for initializer lists in 6.7.9 also apply to compound literals.

And 6.7.9p14 says

  1. An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

you can also use (char []){ "abc" } to the same effect. Notice that even though 6.7.9p14 allows for an array of char be initialized from a string without braces, the rules for compound literals deny this, because (char []) "abc" would look like a cast.

Tags:

C

Gcc