【发布时间】:2017-03-25 12:38:50
【问题描述】:
这是我要运行的代码 -
typedef struct node{
string str;
}node;
string s = "";
node *t = (node *)malloc(sizeof(node));
t->str = s ; // if s is empty, this statement gives segmentation fault.
cout<<t->str<<endl;
【问题讨论】:
-
看起来像是学习
C而不是C++的案例。typedef struct表明了这一点。在C++中,不需要typedef struct,只需struct node { string str; };,下面的答案中涵盖了使用malloc。 -
Eeeek,这看起来更像是用 C++ 编译器编译的 C,而不是正确的 C++。不要使用
malloc并打破typedef struct的习惯。
标签: c++ string segmentation-fault