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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With