Search code examples
cpointersstructc89

Initializing structures with dynamically allocated memory


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;
}

Solution

  • 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 :)