Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ array assign error: invalid array assignment

Tags:

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

like image 582
Alex Ivasyuv Avatar asked Nov 07 '10 17:11

Alex Ivasyuv


1 Answers

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.

like image 173
Stuart Golodetz Avatar answered Oct 14 '22 04:10

Stuart Golodetz