I am trying to create a Binary search tree using C. What I am required to do is insert an id (only numbers) in a node and associate the same node with a name (a string). Using this id, I get to display the tree using InOrder Searching.
The problem is, I got (thanks, internet) the numbers to insert, do the InOrder search.
What I fail to do is associate the string with the node, i.e, I am unable to store the names. I did find an answer to doing the same in a linked list, but I do not seem to comprehend the code. Please, help me.
What I found was memset() {I have no clue what that is} and somehow I am supposed to use stringcpy {I know this, but don't know how to apply it}
My structure code:
struct node
{
int employeeid;
struct node *left;
struct node *right;
char employeename[100];
}*temp=NULL,*link=NULL;
Inside my function I tried to insert the name, but got an error:
printf("Enter the employee name: ");
gets(name);
temp = (struct node *)malloc(sizeof(struct node));
temp->employeeid = data;
temp->employeename = name;
temp->left = temp->right = NULL;
The line of code with the error:
temp->employeename = name;
The error:
error: assignment to expression with array type
What I expected was obviously the code to run. Please help.
You can't use the =
operator with an array. You need to use a function such as strcpy
, strncpy
or memcpy
. And you need to ensure that employeename
is null-terminated.
I would strongly recommend that you use fgets
instead of gets
. In fact you should probably never use gets
. fgets
will take care of the null-termination (assuming that the buffer name
is not larger than employeename
) and will not overrun your buffer.
Don't forget to check malloc
return value. You want to handle error properly rather than crashing when it happens.
Using fgets
, with some error handling and BUFF_SIZE = 100
:
temp = (struct node *)malloc(sizeof(struct node));
if (temp == NULL)
{
printf("Malloc has failed\n");
return (-1);
}
printf("Enter the employee name: ");
fgets(name, BUFF_SIZE, stdin);
temp->employeeid = data;
strcpy(temp->employeename, name);
temp->left = temp->right = NULL;
EDIT:
stdin
is the standard input. To put it simply, this is what normally hold the text that you are writing with your keyboard in your terminal. And this is what scanf
and gets
are using without asking you. Keep in mind that I cut corners with this explanation.
BUFF_SIZE
is a convenient way to represent a constant value. The best way to set it up is to use a define, like this, at the top of your program:
# define BUFF_SIZE 100
int all_your_function()
{
...
This is very useful when you want to: