[英]Segmentation fault when accessing string array of struct
Im currently running into an issue where I have to input words (strings) into a binary search tree and am doing so by putting words(strings) into string arrays, however when I try to put it into the first element, it is segmentation faulting.我目前遇到了一个问题,我必须将单词(字符串)输入到二叉搜索树中,并通过将单词(字符串)放入字符串数组来这样做,但是当我尝试将它放入第一个元素时,它是分段错误.
Here is what I have:这是我所拥有的:
node.h节点.h
typedef struct Node{
char letter;
int asiccValue;
struct Node *left, *right;
string words[99];
int wordCount;
}Node;
tree.cpp树.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;
}
malloc
doesn't call constructors, meaning your string
array isn't initialized. malloc
不调用构造函数,这意味着您的string
数组未初始化。 For any non-trivial type, you really want to avoid malloc
unless you know what you're doing (see also: placement new
).对于任何非平凡类型,除非您知道自己在做什么(另请参阅:placement new
),否则您确实希望避免malloc
。
Using new
should fix your problem.使用new
应该可以解决您的问题。 Make sure you update existing code to use delete
instead of free
.确保更新现有代码以使用delete
而不是free
。 Also, consider getting rid of new
/ delete
entirely, and using make_unique
and friends.另外,考虑完全摆脱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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.