tags:

views:

94

answers:

3

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?

+1  A: 

"abc" can't be cast to a char array since it's not an array to begin with

Eton B.
`"abc"` absolutely is an array - see what `sizeof "abc"` says. The issue is that you can *never* cast to arrays - the first one isn't a cast (even though it looks like one).
caf
A: 

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 folloying should work(not 100% sure):
char *p = &((char[]) "abc");
Or
char *p = &((char[]) "abc")[0];

Dani
Oh I was convinced of your first line of code. But both does not work...
draw
+3  A: 

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};

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";

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

char *p = (char[]){"abc"};
caf
many thanks for your correct answer!
draw