下面的代碼有一些真正奇怪的行爲:將字符串複製到結構通過指針
當選擇= 0時,它返回-1073741819。
當選擇= 1時,它會運行但輸出字符串會混亂。
#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 [selected]'是一個指針。 'sizeof'指針不是你在這裏需要的。你需要找出一個字符串的長度。但嚴重的是,請改用'std :: string'。 – juanchopanza
不要在C++中使用char * anc C數組 –
您忘記取消分配動態分配的所有內存。 – user2079303