我不是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;
Run Code Online (Sandbox Code Playgroud)
我明白了 error: invalid array assignment
为什么它不起作用,如果mStr.message并且hello具有相同的数据类型?
Stu*_*etz 19
因为你不能分配给数组 - 它们不是可修改的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;
}
Run Code Online (Sandbox Code Playgroud)
正如Kedar已经指出的那样,你也在写下数组的末尾.
| 归档时间: |
|
| 查看次数: |
50548 次 |
| 最近记录: |