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