title: Trie Implementation in C++
body: <p>I am trying to implement the trie as shown on the <a href="http://community.topcoder.com/tc?module=Static&amp;d1=tutorials&amp;d2=usingTries" rel="nofollow">TopCoder</a> page. I am modifying it a bit to store the phone numbers of the users. I am getting segmentation fault. Can some one please point out the error.</p>
  
  <pre><code> #include&lt;iostream&gt;
   #include&lt;stdlib.h&gt;
   using namespace std;
  
   struct node{
  int words;
  int prefix;
  long phone;
  struct node* children[26];
   };
  
  struct node* initialize(struct node* root) {
      root = new (struct node);   
      for(int i=0;i&lt;26;i++){
      root-&gt;children[i] = NULL;
      }
      root-&gt;word = 0;
      root-&gt;prefix = 0;
      return root;
   }
  
  int getIndex(char l) {
      if(l&gt;='A' &amp;&amp; l&lt;='Z'){
      return l-'A';
      }else if(l&gt;='a' &amp;&amp; l&lt;='z'){
      return l-'a';
      }
   }
  
    void add(struct node* root, char * name, int data) {
  
      if(*(name)== '\0') {
          root-&gt;words = root-&gt;words+1;
          root-&gt;phone = data;
      } else {        
          root-&gt;prefix = root-&gt;prefix + 1;
          char ch = *name;
          int index = getIndex(ch);
          if(root-&gt;children[ch]==NULL)    {
              struct node* temp = NULL;
              root-&gt;children[ch] = initialize(temp);
          }
          add(root-&gt;children[ch],name++, data);
      }
   }
  
   int main(){
       struct node* root = NULL;
       root = initialize(root);
       add(root,(char *)"test",1111111111);
       add(root,(char *)"teser",2222222222);
           cout&lt;&lt;root-&gt;prefix&lt;&lt;endl;
       return 0;
    }
  </code></pre>
  
  <p>Added a new function after making suggested changes:</p>
  
  <pre><code> void getPhone(struct node* root, char* name){
       while(*(name) != '\0' || root!=NULL) {
           char ch = *name;
           int index = getIndex(ch);
           root = root-&gt;children[ch];
           ++name;
       }
       if(*(name) == '\0'){
           cout&lt;&lt;root-&gt;phone&lt;&lt;endl;
       }
   }
  </code></pre>