2010-11-07 328 views
14

我不是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具有相同的数据类型?

+0

您必须使用strcpy或memcpy函数而不是mstr.message = hello。 – Siddiqui 2010-11-07 17:18:02

+0

行'hello [4096] = 0;'是错误的。这是数组中最后一个元素的一个。只要删除这一行。 – 2010-11-07 17:27:57

回答

13

因为你不能分配给数组 - 它们不是可修改的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; 
} 

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

+0

实际上,Alex的代码**中的数组'mStr.message'和'hello'是**左值,因为表达式&mStr.message和&hello是有效的。 (请参阅C++标准中的第5.3.1节。) – fredoverflow 2010-11-07 17:23:43

+0

是的,你是对的 - 对不起。看来我应该说的是,myStr.message不是*可修改的* l值。 – 2010-11-07 19:05:50

+1

@Stuart:你应该更新你的答案! – 2011-08-16 09:29:32

3

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

14

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

因为标准是这样说的。数组不能分配,只能初始化。

3

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