Probably it is very basic and everyone will shout at me, but I've been trying to fix that for hours and can't take it anymore. I have this structure
struct node
{
Key_Type element;
tree_ptr left, right;
};
And I am trying to put a word into element using strdup like that:
newNode->element = strdup(word);
I understand that it's probably not working because I am trying to allocate a pointer to a normal variable, but I don't know how to fix that.
Table insert(Key_Type word,Table root)
{
struct node *newNode = malloc(sizeof(struct node));
struct node *left = malloc(sizeof(struct node));
struct node *right = malloc(sizeof(struct node));
newNode = root->head;
//fprintf (stderr, "Hi\n");
while(newNode->element != NULL)
{
//printf("%s",word);
if(strcmp(word,newNode->element) == 0)
{
fprintf (stderr, "Hi\n");
return root;
}
while(strcmp(word,newNode->element) == -1)
{
//fprintf (stderr, "Hi\n");
newNode = newNode->left;
//fprintf (stderr, "Hi\n");
}//if
//fprintf (stderr, "Hi\n");
while(strcmp(word,newNode->element) == 1)
{
//fprintf (stderr, "Hi\n");
newNode = newNode->right;
//fprintf (stderr, "Hi\n");
}//else if
}
//createNode(word);
newNode->element = strdup(word);
newNode->left = left;
newNode->right = right;
//fprintf (stderr, "Hi\n");
//printf("%s",root->head->element);
return root;
}
Extending upon @unwind's answer, strdup()
is not a standard C function, and is available on POSIX complaint systems only. Chances are you do not have an strdup
implemented in your system.
Here is a possible implementation of strdup()
char *strdup(const char *c)
{
char *dup = malloc(strlen(c) + 1);
if (dup != NULL)
strcpy(dup, c);
return dup;
}