mantuko
mantuko

Reputation: 143

Error during String declaration

Why does

char line[10] = "1234";

work fine but

char line[10];
line = "1234";

throws an

error: incompatible types in assignment

error?

Upvotes: 0

Views: 694

Answers (3)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215577

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.)

Upvotes: 5

David Heffernan
David Heffernan

Reputation: 613511

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";

Upvotes: 0

Eli Iser
Eli Iser

Reputation: 2834

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.

Upvotes: 1

Related Questions