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

    typedef struct
    {
       int val;
       struct tree *left, *right;
    }tree;

    struct tree *root;

    struct tree *add_vertex(int val) 
    {
      struct tree *root = malloc(sizeof(struct tree*));
      root->val = val;
      root->left = NULL;
      root->right = NULL;
      return root;
    }

    void print_tree(struct tree *root)
    {
      printf("%d\n", root->val);
      if(root->left == NULL)
       return;
      else
       print_tree(root->left);
      if(root->right == NULL)
        return;
      else
        print_tree(root->right);
    } 

    int main() {
      struct tree *root = NULL;

        root = add_vertex(1);
        root->left = add_vertex(2);
        root->right = add_vertex(3);
        root->left->left = add_vertex(4);
        root->left->right = add_vertex(5);
        root->right->left = add_vertex(6);
        root->right->right = add_vertex(7);

        print_tree(root);   

        return 0;
     }

This piece of code is generating

prog.c: In function 'add_vertex':
prog.c:15:9: error: dereferencing pointer to incomplete type 'struct tree'
     root->val = val;
         ^'

removing typedef and doing specific changes it works fine.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    There is no `struct tree` in this code. this is an anonymous untagged struct typedef'd to a `tree` alias which, from what I see you never use anyway. Remove the typedef and instead just use `struct tree { ...etc... };` Are you asking why one would use it as you did? The simple answer is, they *wouldn't* since it leaves pointers to incomplete type in your structure, even if you replaced everything else with just `tree`, those you can't (because there's no "there" there yet). – WhozCraig Nov 15 '19 at 09:46

1 Answers1

0

The problem is

typedef struct
{
   int val;
   struct tree *left, *right;
}tree;

defines a type called tree, which is the type of an unnamed structure.

There is no struct tree defined in your code.

If you remove the typedef, you will have a structure named tree defined, and your code will work properly.


That said, if you want to use typedef, you can do something like

struct tree
{
   int val;
   struct tree *left, *right;
};

typedef struct tree tree;

//......

tree *add_vertex(int val)  //no need to use struct keyword anymore
    {
      tree *root = malloc(sizeof(*root));
      root->val = val;
      root->left = NULL;
      root->right = NULL;
      return root;
    }
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261