Kevin Bracey said:
Because. In C99 you can do:
int *k = (int []) {1,2,3};
which may be what you intended by your code - it creates an unnamed
int array and initialises k to point to it.
Why is that
char *a = "abc";
is legal then?
This has always been fine, of course.
What is odd is not that:
ptr_to_char = "string literal";
is allowed, but rather that:
char array[] = "string literal";
is allowed. It is this form, not the string-literal-as-anonymous-array,
that is the exception in C. All other array initializers require
a sequence of values that map to the right type:
int ai[] = { 1, 2, 3, 0 };
double ad[] = { 1.0, 2.0, 3.0, 0 };
char ac[] = { '1', '2', '3', 0 };
At least C99 improved by allowing a cast.
Couldn't we drop the cast too?
It is not a cast; it just looks like one. The point of the type-name
in parentheses is to supply the type for the array. When the code
above initializes the arrays "ai", "ad", and "ac", the type comes
from the array -- which is why we can also write:
double ad2[] = { 1, '2', 3L, 0.0f };
to get ad2[0] set to 1.0, ad2[1] set to 50.0 on ASCII machines, and
so on. What would you propose do to with, e.g.:
variadic_function( { 'a', 3.14159, 42L } );
if there were no type-hint? (There *are* languages that can handle
the "obvious" meaning of the above, in which there is little
difference between arrays and structures, but they are not C.)
If the array type in parentheses is const-qualified, the C99
anonymous array may be located in read-only storage and there can
be just the one copy. If not, it must be read/write and the copy
must be re-created upon entry to a block (modulo any optimization
allowed via the "as-if" rule). For instance:
void f(void) {
int i, j;
int *ip1, *ip2;
int a1[] = { 1, 2, 3 };
ip1 = a1;
ip2 = (int []) { 4, 5, 6 };
...
/* at this point, assume i and j are both in the [0..2] range */
ip1
= 72;
ip2[j] = -9;
...
}
Here the assignemnt to ip1 changes one of the elements of the
array a1, and the assignment to ip2[j] changes one of the elements
of the anonymous array that might be named a2 if we had given it
a name. When f() returns and is called again later, a1[] and what
might have been called a2[] have to be restored to their original
conditions ({1,2,3} and {4,5,6} respectively).