C++ array assign error: invalid array assignment
70,661
Solution 1
Because you can't assign to arrays -- they're not modifiable l-values. Use strcpy:
#include <string>
struct myStructure
{
char message[4096];
};
int main()
{
std::string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'}
myStructure mStr;
strcpy(mStr.message, myStr.c_str());
return 0;
}
And you're also writing off the end of your array, as Kedar already pointed out.
Solution 2
Why it doesn't work, if
mStr.message
andhello
have the same data type?
Because the standard says so. Arrays cannot be assigned, only initialized.
Solution 3
You need to use memcpy to copy arrays.

Author by
Alex Ivasyuv
Updated on August 18, 2020Comments
-
Alex Ivasyuv over 2 years
I'm not a C++ programmer, so I need some help with arrays. I need to assign an array of chars to some structure, e.g.
struct myStructure { char message[4096]; }; string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'} char hello[4096]; hello[4096] = 0; memcpy(hello, myStr.c_str(), myStr.size()); myStructure mStr; mStr.message = hello;
I get
error: invalid array assignment
Why it doesn't work, if
mStr.message
andhello
have the same data type? -
fredoverflow about 12 yearsActually, the arrays
mStr.message
andhello
in Alex's code are lvalues, because the expressions&mStr.message
and&hello
are valid. (See section 5.3.1 paragraph 3 in the C++ standard.) -
Stuart Golodetz about 12 yearsYup, you're right -- sorry. It seems what I should have said was that myStr.message isn't a modifiable l-value.
-
Claudiu over 7 yearsInteresting. What's the motivation for this? I don't see an issue with assignment to arrays constituting copying the memory over.
-
MaEtUgR about 2 years@Claudiu My assumption would be it has to do with the fact that the array variable name itself in C refers to the pointer of the start address of the array and the type of the arrray does in principle not contain information about it's length. So a direct assignment would be a pointer assignment which you rarely want and an automatic array copy is not possible because the length is unkown from the type. With memcpy you have to specify the length.