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;
}
我在主线的第 6 行出现错误
root->left = mkTreeNode("Does it have legs?n", NULL, NULL);
"取消引用指向不完整类型的指针";有什么想法吗?我需要另一个malloc
什么的吗?
如果显示的代码位于不同的文件中,则不清楚struct
声明是否从包含main()
的 C 文件中可见。如果不是,则在尝试访问结构的字段时会收到该错误。
更新 你说它都在一个文件中,尽管它看起来不像那样。在这种情况下,请注意顺序很重要,struct
声明必须出现在(上)main()
之前。
基本上,这应该有效:
#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;
}