1

Im working on a Binary Search Tree in C atm, works all fine, nodes are inserted, found, printed etc. BUT, the values they have are not correct. Every node in my tree has a phone number (phone) and a name (name). The phone numbers are not the problem, but the names. For example if I have my root with the number 1 and the name is supposed to be "Mike", it says number=1 and name=1

Same for every other node. Number=Name. Why? I guess it has something to do with the value being a string and not an int, right? The important part in my code would be the following then:

void bst_insert_node(bstree* bst, unsigned long phone, char *name) {

bst_node* tmp=bst->root;
bst_node* tmp2;
bst_node* new_node=(bst_node*)malloc(sizeof(bst_node));

new_node->phone=phone;
new_node->name=name; // THIS LINE
new_node->left=new_node->right=NULL;

What would I have to change? I tried several things now, but nothing worked..

ykykyk
  • 11
  • 3
  • 1
    Welcome to Stack Overflow! [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Dec 25 '16 at 16:05
  • Welcome to Stack Overflow! You mind creating a [___MCVE___](http://stackoverflow.com/help/mcve)? – Sourav Ghosh Dec 25 '16 at 16:05
  • Thx for the link! Didnt know that. And my posted code is not enough? What can I do better? I actually thought thats the right way.. – ykykyk Dec 25 '16 at 16:17

1 Answers1

2

As you said, the problem is that the name is a string type which is actually char*. Therefore you are assigning only a pointer to string. You have to copy the string. Something like this:

new_node->name = malloc((strlen(name)+1) * sizeof(char)); // allocate
strcpy(new_node->name, name); // copy the content

Mind the +1 in the malloc statement. You need to allocate one additional char for the string-terminating character ('\0').

Adam
  • 177
  • 1
  • 7