2017-04-03 44 views
0
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这样的成员。我怎么能解决这个问题,如果我想要一个新的节点添加到联系人如何在函数中使用struct

+1

您从未将'newnode'设置为任何值。在将其传递给函数之前,您也不设置“联系人”。您的代码遍布全局的未定义行为。 – kaylum

+1

C或C++?下定决心。 – molbdnilo

+1

另外你还没有设置'contacts' – kuro

回答

0

你没有任何stoarge在main或测试分配给contacts或将其设置为NULL,如果它是空的add

如果你很幸运,因为你在程序开始时是正确的,所以当你通过它时,contacts是NULL,所以add顶部的if测试会随着分段冲突而崩溃。

此外,您使用newNode而不分配空间。