Error during String declaration
Why does
char line[10] = "1234";
work fine but
char line[10];
line = "1234";
throws an
error: incompatible types in assign开发者_运维百科ment
error?
Arrays are not pointers. In your second example, line
is a non-modifiable lvalue, but more importantly, no matter what you put on the righthand side, it can't have type char [10]
(because arrays decay to pointers in non-lvalue context) and thus the types can never match.
For what it's worth, a string literal has type char [N]
, not const char [N]
and especially not const char *
, despite the fact that attempts to modify it invoke undefined behavior. (Here N
is the length of the quoted text in bytes, including the added null terminator.)
The first line works because it performs an initialization of the char
array with data. It would be the same as:
char line[10] = {'1', '2', '3', '4', '\0'};
In the second example, the type of "1234"
is const char*
, since it is a pointer to a constant char
array. You're trying to assign a const char*
to a char*
, which is illegal. The correct way to assign a constant (or other) string to a string variable is to use strcpy
, strncpy
, or any other string handling function.
Because those are the rules of the language, as others have explained. I'd write it like this though and avoid declaring up-front how many characters there are.
const char* line = "1234";
精彩评论