【发布时间】:2016-02-29 10:58:23
【问题描述】:
以下代码有一些非常奇怪的行为:
When chosen = 0, it returns -1073741819.
When chosen = 1, it runs but the output strings are messed up.
#include <iostream>
#include <cstring>
using namespace std;
char* name[2] = {"WithoutSpaces","With spaces"};
struct entity{
char* name;
};
struct entity *foo1, *foo2;
int main(void){
foo1 = new entity;
foo2 = new entity;
int chosen = 1;
foo1->name = new char[sizeof(name[chosen])+1];
strcpy(foo1->name,name[chosen]);
foo2->name = new char[sizeof(name[chosen])+1];
strcpy(foo2->name,name[chosen]);
cout << foo1->name <<endl;
cout << foo2->name <<endl;
return 0;
}
发生了什么?
【问题讨论】:
-
name[chosen]是一个指针。sizeof指针不是你需要的。您需要找出字符串的长度。但说真的,请改用std::string。 -
不要在 C++ 中使用 char* anc C 数组
-
您忘记释放所有动态分配的内存。
-
@juanchopanza 所说的关于
std::string的内容延伸到像std::unique_ptr这样的智能指针。我看到四个news 没有deletes。