21

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?

3 Answers 3

24

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 */
2
  • 1
    This is excellent, because now I can do this: sizeof((char[]){"abcde"})
    – Michael
    Jun 16, 2012 at 19:39
  • 1
    @Michael: You could always do sizeof "abcde" which is exactly the same - the only differences between the compound literal and the string literal are that the compound literal is modifiable, and that the string literal may share storage with other string literals.
    – caf
    Dec 7, 2012 at 0:56
3

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.

-1

The first example isn't casting it's array creation. And there is huge diffrence between char[] and char* : the first one is the array itself and second one is pointer to array. The following should work (not 100% sure):

char *p = &((char[]) "abc");  

Or

char *p = &((char[]) "abc")[0];
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.