[编者注:我已经编辑了标题,试图在将来对其他人有用.为了给回答者一个信誉,这只是"为什么这不起作用?" 他们回答的问题!]
top -> ...无论Node*尝试将哪些代码推送到矢量子代,以下代码都会在具有分段错误的行中崩溃.有谁知道这可能导致什么?
struct Node
{
string data;
struct Node* parent;
vector<struct Node*> children;
};
struct Node* push(string word, struct Node* top)
{
Node* temp = (struct Node*) malloc(sizeof(struct Node));
temp -> data = word;
temp -> parent = top;
return temp;
}
int main()
{
Node* top = push("blah", NULL);
Node* temp = NULL;
top -> children.push_back(temp);
}
Run Code Online (Sandbox Code Playgroud)
问题是malloc不会调用构造函数.而且你依靠children要构建的向量.
更换:
Node* temp = (struct Node*) malloc(sizeof(struct Node));
Run Code Online (Sandbox Code Playgroud)
附:
Node* temp = new Node;
Run Code Online (Sandbox Code Playgroud)
malloc(来自C)和new(来自C++)将分配你需要的内存,但只会new调用所需的构造函数,因为C不使用它们.如果你不肯定你需要malloc,请使用new.