In C why is it legal to do
char * str = "Hello";
but illegal to do
int * arr = {0,1,2,3};
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.
General syntax of pointer declaration is, datatype *pointer_name; Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing.
& is a reference operator which means it is used to get the memory location of the variable. So 'a' is an integer variable and by doing &a, we are getting the location where a is stored in the memory and then letting the pointer point to that location. This is the first method of initializing a pointer in C.
Value-initialization of a pointer initializes it to a null pointer value; therefore both initializer lists are equivalent. To zero-initialize an object or reference of type T means: if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T.
I guess that's just how initializers work in C. However, you can do:
int *v = (int[]){1, 2, 3}; /* C99. */
As for C89:
"A string"
, when used outside char
array initialization, is a string literal; the standard says that when you use a string literal it's as if you created a global char
array initialized to that value and wrote its name instead of the literal (there's also the additional restriction that any attempt to modify a string literal results in undefined behavior). In your code you are initializing a char *
with a string literal, which decays to a char
pointer and everything works fine.
However, if you use a string literal to initialize a char
array, several magic rules get in action, so it is no longer "as if an array ... etc" (which would not work in array initialization), but it's just a nice way to tell the compiler how the array should be initialized.
The {1, 2, 3}
way to initialize arrays keeps just this semantic: it's only for initialization of array, it's not an "array literal".
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