C++ 数组赋值错误:数组赋值无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4118732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:34:38  来源:igfitidea点击:

C++ array assign error: invalid array assignment

c++carrays

提问by Alex Ivasyuv

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.

我不是 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;

I get error: invalid array assignment

我得到 error: invalid array assignment

Why it doesn't work, if mStr.messageand hellohave the same data type?

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

采纳答案by Stuart Golodetz

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

因为您不能分配给数组——它们不是可修改的左值。使用 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.

正如Kedar 已经指出的那样,您也在注销数组的末尾。

回答by fredoverflow

Why it doesn't work, if mStr.messageand hellohave the same data type?

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

Because the standard says so. Arrays cannot be assigned, only initialized.

因为标准是这么说的。数组不能赋值,只能初始化。

回答by Puppy

You need to use memcpy to copy arrays.

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

回答by Puppy

The declaration char hello[4096];assigns stack space for 4096 chars, indexed from 0to 4095. Hence, hello[4096]is invalid.

该声明char hello[4096];为 4096 个字符分配了堆栈空间,索引从04095。因此,hello[4096]无效。