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;
我得到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;,c++,c,arrays,C++,C,Arrays,我得到错误:数组分配无效 如果mStr.message和hello具有相同的数据类型,为什么它不工作?声明char hello[4096]为4096个字符分配堆栈空间,索引范围从0到4095。 因此,hello[4096]无效 如果mStr.message和hello具有相同的数据类型,为什么它不工作 因为标准是这么说的。无法分配数组,只能进行初始化。您需要使用memcpy来复制数组。因为您无法分配数组--它们是不可修改的l值。使用strcpy: #include <string>
错误:数组分配无效
如果
mStr.message
和hello
具有相同的数据类型,为什么它不工作?声明char hello[4096]
为4096个字符分配堆栈空间,索引范围从0
到4095
。
因此,hello[4096]
无效
如果mStr.message
和hello
具有相同的数据类型,为什么它不工作
因为标准是这么说的。无法分配数组,只能进行初始化。您需要使用memcpy来复制数组。因为您无法分配数组--它们是不可修改的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;
}
#包括
结构myStructure
{
字符消息[4096];
};
int main()
{
std::string myStr=“hello”//我需要创建{'h','e','l','l','o'}
myStructure-mStr;
strcpy(mStr.message,myStr.c_str());
返回0;
}
正如Kedar已经指出的那样,您也在注销数组的结尾。您必须使用strcpy或memcpy函数,而不是mstr.message=hello。行
hello[4096]=0代码>是错误的。这是数组最后一个元素的过去一次。删除这一行。实际上,Alex代码中的数组mStr.message
和hello
是左值,因为表达式&mStr.message
和&hello
是有效的。(参见C++标准第5.3.1节第3段)YYUP,你说得对,对不起。看来我应该说的是myStr.message不是一个可修改的l值。这样做的动机是什么?我不认为对数组的赋值构成复制内存的问题。@Claudiu我的假设是,它与C中的数组变量名本身引用数组起始地址的指针有关,并且数组的类型原则上不包含有关其长度的信息。因此,直接赋值将是您很少需要的指针赋值,而自动数组复制是不可能的,因为类型的长度是未知的。使用memcpy时,必须指定长度。