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

Ale*_*yuv 20 c c++ arrays

我不是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;
Run Code Online (Sandbox Code Playgroud)

我明白了 error: invalid array assignment

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

Stu*_*etz 19

因为你不能分配给数组 - 它们不是可修改的l值.使用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;
}
Run Code Online (Sandbox Code Playgroud)

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


fre*_*low 14

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

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