C++中char数组赋值报‘expression must be a modifiable lvalue’错误原因
Hey there! Let's break down why that error is popping up when you try to assign a string literal directly to your char array in C++. This is a super common gotcha for folks moving from C to C++, especially since C++ enforces stricter rules around array handling.
The Core Problem: Array Names Are Non-Modifiable Lvalues
When you declare char message[sizeArr];, the name message isn't a regular variable you can reassign at will. It acts as a non-modifiable lvalue—think of it as a constant pointer pointing to the first element of your array. When you write message = "I am sending this back";, you're trying to overwrite that fixed pointer with the address of the string literal, which both C and C++ explicitly forbid.
Wait, Did I Do This in C Before?
Actually, no—you probably confused initialization with assignment! In both languages, this is totally valid (it's initialization):
char message[sizeArr] = "I am sending this back";
Here, the compiler copies the characters of the string literal into your array when it's first created. But splitting declaration and assignment like you did:
char message[sizeArr]; message = "I am sending this back"; // Invalid in C AND C++!
This never was standard-compliant. Some C compilers might let it slide with a warning, but C++ calls it out immediately with the "modifiable lvalue" error to make it clear you're breaking the rules.
How to Fix It
You've got a few solid options depending on your use case:
- Use initialization instead of assignment: If you can set the string when you declare the array, this is the simplest approach (as shown above).
- Use a string copy function: For cases where you need to update the array after declaration, use
strncpy(safer thanstrcpyto avoid buffer overflows) from the<cstring>header:#include <cstring> int main() { char message[sizeArr]; strncpy(message, "I am sending this back", sizeArr - 1); message[sizeArr - 1] = '\0'; // Ensure the string ends with a null character } - Switch to
std::string(the C++ way): If you're working in C++, using the standard library'sstd::stringis way easier and safer—it supports direct assignment out of the box:#include <string> int main() { std::string message; message = "I am sending this back"; // Totally valid and hassle-free! }
内容的提问来源于stack exchange,提问作者Papbad




