I'm not quite sure how to iterate through a string and malloc a new node to properly insert each letter into a trie for pset5/6 (2014/15). Here is the relevant code that I've come up with so far, probably other things wrong with it too. At the moment, all I'm trying to do is insert one hard-coded string into a trie structure.

// create struct for nodes
typedef struct node
    bool is_word;
    struct node* children[26];
} node;

// initialise a string to load
char* word = "cat";

// store 1st letter as a value between 0 and 25
int letter = (toupper(word[0])) - 65;

// create pointer to root node, check for null
node* root = malloc(sizeof(node));
if (root == NULL)
    return 1;

// create pointer to new node, check for null
node* new = malloc(sizeof(node));
if (new == NULL)
    return 1;

// insert first letter into trie
root->children[letter] = new;   

// pseudocode for inserting second letter into trie
new = malloc(sizeof(node));
root->children[first_letter]->children[second_letter]= new;

My understanding is that the first insertion statement points root->children[letter] to the heap memory that new is also pointing to, meaning that when it comes to inserting the next letter into the trie I can just re-assign new to some new heap memory. So new is really just a temporary name for a node before it gets inserted into the trie. Have I got this right?


I duplicated this question on reddit and have been informed that I am correct, I think, so I guess consider this questioned answered unless someone else wishes to add something. Not sure if should close this question or not...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .