C++ array assign error: invalid array assignment [duplicate]

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 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 and hello have the same data type?

asked Nov 7, 2010 at 17:07 Alex Ivasyuv Alex Ivasyuv 8,744 17 17 gold badges 75 75 silver badges 91 91 bronze badges You have to use strcpy or memcpy function instead of mstr.message = hello. Commented Nov 7, 2010 at 17:18

The line hello[4096] = 0; is wrong. This is one past the last element of the array. Just remove this line.

Commented Nov 7, 2010 at 17:27

4 Answers 4

Because you can't assign to arrays -- they're not modifiable l-values. Use strcpy:

#include struct myStructure < char message[4096]; >; int main() < std::string myStr = "hello"; // I need to create 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.

answered Nov 7, 2010 at 17:17 Stuart Golodetz Stuart Golodetz 20.6k 4 4 gold badges 53 53 silver badges 81 81 bronze badges

Actually, the arrays mStr.message and hello 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.)

Commented Nov 7, 2010 at 17:23

Yup, you're right -- sorry. It seems what I should have said was that myStr.message isn't a modifiable l-value.

Commented Nov 7, 2010 at 19:05

Interesting. What's the motivation for this? I don't see an issue with assignment to arrays constituting copying the memory over.

Commented Jul 21, 2015 at 21:27

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