Why is this syntax illegal in C?
int *a = {1,2,3};
Aren't arrays and pointers the same thing? Why would this work and not the above?
int a[] = {1,2,3};
int *b = a;
Why is this syntax illegal in C?
int *a = {1,2,3};
Aren't arrays and pointers the same thing? Why would this work and not the above?
int a[] = {1,2,3};
int *b = a;
Why is this syntax illegal in C?
In int a[] = {1,2,3};
, the {1,2,3}
is a syntax for providing initial values of the things being initialized. A list of values in braces is a general notation for listing initial values. It is not a notation for representing an array.
The declaration says a
is an array, but that is just in its int a[]
part. The {1,2,3}
does not indicate an array—it just provides a list of values, and it could be used for non-array objects, such as providing values for the members of a structure.
In int *a = {1,2,3};
, the int *a
part defines a
to be a pointer. A pointer just has one value in it—the address of something (or null). So it does not make sense to initialize it with multiple values. To initialize a pointer, you need to provide an address for it to point to.
There is a notation in C for representing an array of given values. It is called a compound literal, and can be used for types in general, not just arrays. Its syntax is “(type) { initial values }”. So we can create an array with (int []) {1, 2, 3}
. A pointer could be defined and initialized to point to this array with int *a = (int []) {1, 2, 3};
. However, this should be done with care. Such an array is temporary (has automatic storage duration that ends when execution of its associated block ends) when defined inside a function, so the pointer will become invalid when the function returns (or before, if it is in an inner block).