我目前遇到了一个问题,我必须将单词(字符串)输入到二进制搜索树中,并通过将单词(字符串)放入字符串数组来做到这一点,但是当我试图将其放入第一个元素时,它是分段错误。
这就是我所拥有的:
node.h
typedef struct Node{
char letter;
int asiccValue;
struct Node *left, *right;
string words[99];
int wordCount;
}Node;tree.cpp
// This function creates new nodes as needed
Node *createNode(string word){
// Assigns values
struct Node *temp = (Node*)malloc(sizeof(Node));
temp->letter = word[0];
temp->asiccValue = (int)word[0];
temp->left = NULL;
temp->right = NULL;
temp->words[0] = word;
temp->wordCount = 1;
return temp;
}发布于 2020-10-13 12:53:26
malloc不调用构造函数,这意味着您的string数组没有初始化。对于任何非平凡的类型,除非您知道自己在做什么,否则您确实希望避免使用malloc (另请参阅: placement new)。
使用new应该可以解决您的问题。确保将现有代码更新为使用delete而不是free。此外,考虑完全摆脱new/delete,并使用make_unique和朋友。
Node *createNode(string word){
// Assigns values
Node * temp = new Node;
temp->letter = word[0];
temp->asiccValue = (int)word[0];
temp->left = NULL;
temp->right = NULL;
temp->words[0] = word;
temp->wordCount = 1;
return temp;
}https://stackoverflow.com/questions/64327983
复制相似问题