I can't figure out how to copy a string from inputString
to newNode->data
.
My struct looks like this:
typedef struct node {
char *data;
struct node *left;
struct node *right;
} node;
And the function in questions looks like this:
node* addToTree(char inputString[]) {
node *newNode;
if ((newNode = malloc(sizeof(node*))) == NULL) {
printf("Error: could not allocate memory");
exit(-1);
}
if ((newNode->data = malloc(strlen(inputString) + 1)) == NULL) {
printf("Error: could not allocate memory");
exit(-1);
}
/* This line of code doesn't seem to copy anything to newNode->data.
This is the way I believe should work, however I don't understand what the
problem with it is. I have tried strlcpy and strncpy as well. */
strcpy(newNode->data, inputString);
/* The line below here seems to work when I print the value
within the function, but some of the values are garbage when
I try to use them later on in the program. */
newNode->data = inputString;
newNode->left = NULL;
newNode->right = NULL;
printf("Input string: %s\n", inputString);
printf("New node data: %s\n", newNode->data);
return newNode;
}