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

查看:2031
本文介绍了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.message 你好有相同的数据类型?

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

而你也注销阵列的结束,基达已经指出的那样。

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

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

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