Question

I am having a hard time figuring out how to dynamically allocate memory and then initialize a struct with that memory. I am trying to make a binary tree and then set the children to have NULL as their 'word', this was I can test for NULL and insert more nodes as necessary. Here's what I have so far.

#include <stdio.h>
#include <stdlib.h>

struct node{
   char* word;
   int count;
   struct node* leftchild;
   struct node* rightchild;
};

int main(void){
   struct node *rootnode=malloc(sizeof(struct node));
   scanf("%s ",rootnode.word);
   rootnode.count=countchars(rootnode.word);/*haven't written this func yet*/

   rootnode.leftchild=malloc(sizeof(struct node));
   struct node* leftchild = rootnode.leftchild;
   rootnode.leftchild.word=NULL;

   rootnode.rightchild=malloc(sizeof(struct node));
   struct node* rightchild = rootnode.rightchild;
   rootnode.rightchild.word=NULL;
}
Was it helpful?

Solution 3

struct node * is a pointer type. To access its values, you need to dereference them. The following shows what you may have been going for:

typedef struct node_t{
    char* word;
    int count;
    struct node_t* leftchild;
    struct node_t* rightchild;
} node;

int main(void){
    node *rootnode = (node*)malloc(sizeof(node));
    //scanf("%s ", rootnode.word);
    //rootnode.count = countchars(rootnode.word);/*haven't written this func yet*/
    rootnode->leftchild = (node*)malloc(sizeof(node));

    node* leftchild = rootnode->leftchild;
    leftchild->word = NULL;
    rootnode->rightchild = (node*)malloc(sizeof(node));

    node* rightchild = rootnode->rightchild;
    rightchild->word = NULL;
    return 0;
}

Note that the scanf line is commented - you need to allocate space for the word buffer before you can read into it. I leave that as an exercise to you :)

OTHER TIPS

Your following logic is not correct:

struct node *rootnode=malloc(sizeof(struct node));
scanf("%s ",rootnode.word);
rootnode.count=countchars(rootnode.word);/*haven't written this func yet*/

In the above code, you have allocated the memory for the struct node. Now word is of pointer of type char. So far you have allocated the memory which can store the address into this variable.

Now you need to allocate the memory to copy into this particular variable. You need to find or define the maximum length of string here. For an example(100)

rootnode.word = malloc(100*sizeof(char));
// Now you can use this memory further in your program.

BTW you need to write the logic to free the memory as well.

Just for starters, you need to allocate the buffer used for "word" when you need it. Next, the usual practice is just to set the child pointers to NULL to indicate non-existance.

So

node.count=strlen(string); /* hope this is what you want, if not use strlen(string on next line) */
node.word = malloc(node.count+1);
strcpy(node.word, string);
node.leftChild = node.rightChild = NULL;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top