2014-05-19 74 views
1

我正在编写一个二叉树程序,其中每个节点都包含一个结构体。作为指针新手,我不知道如何解决我得到的这个错误。c树结构表达式必须具有类类型

这是我的结构:

//inventory definition 
typedef struct inventory 
{ 
    char invName[36]; 
    int invPartNo; 
    int invQOH; 
    float invUnitCost; 
    float invPrice; 
}item; 

//tree definition 
struct btree { 
    item *data; 
    struct btree *left; 
    struct btree *right; 
} ; 

而在这两个函数,我得到了“表达式必须有一个类类型”的错误:

struct btree *binary_search(struct btree *tree, int data) 
{ 
    if (tree==NULL) return NULL; 
    else if (data == tree->data.invPartNo) //tree in this line is highlighted red with the error 
     return tree; 
    else if (data < tree->data.invPartNo) //tree in this line is highlighted red with the error 
     return(binary_search(tree->left, data)); 
    else 
     return(binary_search(tree->right, data)); 
} 


btree *Insert(btree *node, inventory i) 
{ 
    if(node == NULL) 
    { 
     btree *temp; 
     temp = (btree *)malloc(sizeof(btree)); 
     temp->data = i; 
     temp->left = temp->right = NULL; 
     return temp; 
    } 
    if(i.invPartNo > node->data.invPartNo) //node is highlighted with error 
    { 
     node->right = Insert(node->right, i); 
    } 
    else if(i.invPartNo < node->data.invPartNo) //node is highlighted with error 
    { 
     node->left = Insert(node->left, i); 
    } 
    return node; 
} 
+3

成员'data'是一个指针。在你的代码中还有其他一些不一致的地方(比如使用'inventory'作为类型),你确定你正在编程C而不是C++吗?另外,还有一些其他的错误我很惊讶,你不会问(比如将一个非指针结构赋值给一个指向结构体的指针)。 –

+0

'data ==(tree-> data) - > invPartNo'....所有'data'都是节点中的指针 – GoldRoger

+0

请不要强制'malloc'的返回值 –

回答

2

node->data指针到一个item类型,所以.不适合它时试图选择一个子字段。

您需要使用->,如(node->data)->invPartNo

但我不能完全肯定为什么你会有效载荷分离到另一个结构(一)。我可能会做到这一切一个结构,然后只使用操纵指针树重构。换句话说,这样的:

struct btree { 
    item data;   // Now it IS "node->data.something". 
    struct btree *left; 
    struct btree *right; 
}; 

(一)有因为有时候有效的原因,这比如如果B树的有效载荷是像一个链表另一个集合,或者如果你想树木能够存储任意数据类型。但是在这里看来,只有一个间接层次,即树节点本身,会更简单。

相关问题