C++ 数组赋值错误:数组赋值无效 [英] C++ array assign error: invalid array assignment

查看:89
本文介绍了C++ 数组赋值错误:数组赋值无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是 C++ 程序员,所以我需要一些有关数组的帮助.我需要将一个字符数组分配给某个结构,例如

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;

我收到错误:数组分配无效

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

Why it doesn't work, if mStr.message and hello have the same data type?

推荐答案

因为您不能分配给数组——它们不是可修改的左值.使用 strcpy:

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

正如 Kedar 已经指出的那样,您还注销了数组的末尾.

And you're also writing off the end of your array, as Kedar already pointed out.

这篇关于C++ 数组赋值错误:数组赋值无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆