The following code is perfect valid,
int *ia = (int[]){1,3,5,7};
but when I compile the next line of code,
char *p = (char[]) "abc";
gcc says
test.c:87: error: cast specifies array type
It seems they are casted in the same way. Why did the second one get an err msg?
As you guys said, "abc" is a pointer, which cannot be converted to be a pointer. So my another question: why does
char[] s = "abc";
is valid. How does the above line of code work when compiling?
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:
- 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
- All the semantic rules for initializer lists in 6.7.9 also apply to compound literals.
And 6.7.9p14 says
- 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With