"derefeerncing pointer to incomplete type" - trying to make tree nodes in animal guessing game C

StackOverflow https://stackoverflow.com/questions/22095650

  •  18-10-2022
  •  | 
  •  

Question

main:

int main(int argc, char *argv[])
{   
    printf("Please think of an animal. I will try to find out what it is by asking you some yes/no questions.");
    struct treenode *root = mkTreeNode("Is it a reptile?\n", NULL, NULL);
    struct treenode *selectedNode = root;
    root->left = mkTreeNode("Does it have legs?\n", NULL, NULL);
    root->right = mkTreeNode("Is it a mammal?\n", NULL, NULL);
    root->left->left = mkTreeNode("Crocodile", NULL, NULL);
    root->right->left = mkTreeNode("Elephnt", NULL, NULL);

mkTreeNode:

struct treenode {
 char *animal;
 struct treenode *left;
 struct treenode *right;
};

struct treenode *mkTreeNode(char *str, struct treenode *lChild, struct treenode *rChild) {

struct treenode *node = malloc(sizeof(struct treenode));

  node -> left = lChild;
  node -> right = rChild;
  node -> animal = str;

  return node;
}

I get an error on line 6 in main

root->left = mkTreeNode("Does it have legs?\n", NULL, NULL);

"dereferencing pointer to incomplete type"; any ideas? Do I need another malloc or something?

No correct solution

OTHER TIPS

If the code shown is in different files, then it's not clear if the struct declaration is visible from the C file that has main() in it. If it isn't, you get that error when trying to access fields of the structure.

UPDATE You say that it's all in one file, although it doesn't look like that. In that case, note that order matters, the struct declaration must appear before (above) main().

Basically, this should work:

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

struct treenode {
 char *animal;
 struct treenode *left;
 struct treenode *right;
};

struct treenode *mkTreeNode(char *str, struct treenode *lChild, struct treenode *rChild)
{
  struct treenode *node = malloc(sizeof *node);
  node->left = lChild;
  node->right = rChild;
  node->animal = str;
  return node;
}

int main(int argc, char *argv[])
{   
  printf("Please think of an animal. I will try to find out what it is by asking you some yes/no questions.");
  struct treenode *root = mkTreeNode("Is it a reptile?\n", NULL, NULL);
  struct treenode *selectedNode = root;
  root->left = mkTreeNode("Does it have legs?\n", NULL, NULL);
  root->right = mkTreeNode("Is it a mammal?\n", NULL, NULL);
  root->left->left = mkTreeNode("Crocodile", NULL, NULL);
  root->right->left = mkTreeNode("Elephant", NULL, NULL);
  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top