In C why is it legal to d开发者_如何学Pythono
char * str = "Hello";
but illegal to do
int * arr = {0,1,2,3};
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".
In the case of:
char * str = "Hello";
"Hello"
is a string literal. It's loaded into memory (but often read-only) when the program is run, and has a memory address that can be assigned to a pointer like char *str
. String literals like this are an exception, though.
With:
int * arr = {0,1,2,3};
..you're effectively trying to point at an array that hasn't been put anywhere in particular in memory. arr
is a pointer, not an array; it holds a memory address, but does not itself have storage for the array data. If you use int arr[]
instead of int *arr
, then it works, because an array like that is associated with storage for its contents. Though the array decays to a pointer to its data in many contexts, it's not the same thing.
Even with string literals, char *str = "Hello";
and char str[] = "Hello";
do different things. The first sets the pointer str
to point at the string literal, and the second initializes the array str
with the values from "Hello"
. The array has storage for its data associated with it, but the pointer just points at data that happens to be loaded into memory somewhere already.
Because there's no point in declaring and initializing a pointer to an int array, when the array name can be used as a pointer to the first element. After
int arr[] = { 0, 1, 2, 3 };
you can use arr
like an int *
in almost all contexts (the exception being as operand to sizeof
).
... or you can abuse the string literals and store the numbers as a string literal, which for a little endian machine will look as follows:
int * arr = (int *)"\0\0\0\0\1\0\0\0\2\0\0\0\3\0\0\0";
精彩评论