typedef struct node {
int num_children;
struct node *children[ALPHABET_LENGTH];
} trie_node;
void add(char* a, trie_node* node){//need to make sure a is not NULL at beginning
trie_node* newNode;
int i;
if (a != NULL && node->children[(int)a[0] - 97] == NULL)
{
node->num_children++;
//initialize the children array
for (i = 0; i < ALPHABET_LENGTH; i++)
{
if (newNode->children[i] != NULL)
{
newNode->children[i] = NULL;
}
}
newNode -> num_children = 0;
a++;
add(a, newNode);
}
else if (a != NULL && node->children[(int)a[0] - 97] != NULL){
a++;
node->num_children++;
add(a, node->children[(int)a[0] - 97]);
} else{//a == NULL, which means end of the add procedure
return;
}
}
int main()
{
char* s = "add abc";
trie_node* contacts;
add(s,contacts);
return 0;
}
当我在main函数中初始化struct trie_node时,我可以访问所有联系人成员。但是,当我在add函数中执行此操作时,newNode不起作用。我无法访问newNode下的num_children等成员。如果我想向联系人添加新节点,我该如何解决?
答案 0 :(得分:0)
您不会将任何目标分配给contacts
或将其设置为NULL
中的main
,或者在add
中测试它是否为空。
如果你很幸运,因为你在程序开始时就是正确的,当你传递它时contacts
为NULL,所以add
顶部的if测试会因分段违规而崩溃
此外,您使用newNode
而不为其分配空间。