Hi all,
I'm relatively new to C and can't for the life of me figure out what I'm doing wrong! I have a simple struct setup to create a binary tree with a char * called 'name'. I also have a local variable called 'name' of the same type. When I write to the local variable 'name' the version in the struct also gets written to. I have no idea why this is but I'm guessing it's something to do with how the memory is being written to. The code below is a very simple example of what is going wrong:
Code:
#include <stdio.h>
#define MAX_INPUT_SIZE 100
int main() {
struct node {
char *name;
struct node *left;
struct node *right;
};
struct node *root;
root = NULL;
root = malloc(sizeof(struct node));
root->name = NULL;
char *name;
/* Stores user input */
char in[MAX_INPUT_SIZE];
/* Used for checking presence of '\n' in expr */
char *p;
/* Used to check if user has finished inputting numbers */
int exp_in = 1;
/* Loop whilst the user wants to add more names */
while (exp_in) {
if (fgets(in, sizeof(in), stdin) != NULL) {
/* Remove '\n' if fgets adds it */
if ((p = strchr(in, '\n')) != NULL)
*p = '\0';
/* Check to see if user wants to exit */
if (strcmp(in, ".") == 0) {
exp_in = 0;
/* Otherwise handle the input and add to tree */
} else {
/* Loop counter, variable to store string length and variable to store i at start of phone number */
int i, len = strlen(in), j;
/* Get name from input */
for (i=0; (i < len) && (in[i] != ' '); i++)
name[i] = in[i];
name[i] = '\0';
printf("%s\n", (root->name != NULL)?root->name:"");
root->name = name;
}
}
}
}
Can anyone offer any ideas on what could be going wrong?
Cheers,
James