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..

3

1 Answer 1

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').

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.