C ++数组分配错误:无效的数组赋值

我不是C ++程序员,所以我需要一些数组帮助。 我需要为某些结构分配一个字符数组,例如

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; 

我收到error: invalid array assignment

如果mStr.messagehello具有相同的数据类型,为什么它不起作用?

因为你不能分配给数组 – 它们不是可修改的l值。 使用strcpy:

 #include  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; } 

正如Kedar已经指出的那样,你也在写出数组的末尾。

如果mStr.messagehello具有相同的数据类型,为什么它不起作用?

因为标准这样说。 无法分配数组,仅初始化。

声明char hello[4096]; 为4096个字符分配堆栈空间,索引范围为04095 。 因此, hello[4096]是无效的。

您需要使用memcpy来复制数组。