For the following structure
struct node{
char * data;
struct node *left;
struct node *right;
} *root=NULL,*temp;
you would have to separately allocate memory for data
.
Just the following would not work
root=(struct node*)malloc(sizeof(struct node));
root->data = x;
Solution strategy 1: Allocate memory according to need. I.e. allocate enough memory to hold the string for that node. Here, the code has to properly manage node->data
, i.e. suitably allocate and de-allocate.
free( root->data ); // free previously allocated memory, if any
root->data = strdup( x ); // equivalent to malloc and memcpy
As an improvement, the memory request for data
may be included in the malloc
for node, thereby (a) avoiding memory fragmentation, (b) avoiding (per-malloc) overhead, (c) avoiding extra work while releasing memory (free()
of node would free memory of data
).
struct node {
struct node *left;
struct node *right;
char * data;
};
size_t const xLen = strlen( x );
root = malloc( sizeof *root + xLen );
strncpy( root + sizeof root->left + sizeof root->right, x, xLen );
Solution strategy 2: Have the node contain necessary memory for the string. This way, there is no hassle to allocate and deallocate separately for the string. However, on the flip side, the upper limit becomes same for all strings. (It is a trade-off.)
char data[ MaxDataLen ]; // earlier, enum { MaxDataLen = 80 };
strncpy( root->data, x, MaxDataLen - 1 ); // copy chars
root->data[ MaxDataLen - 1 ] = 0; // NULL termination