Brian
Brian

Reputation: 187

c binary tree insert function pointer

I am trying to make a binary tree program where each tree node contains a struct of 'inventory'.

I am currently getting an error in my insert function that causes compile to fail. The error I am getting is:

left of '.invPartNo' must have class/struct/union
type is 'inventory *'
did you intend to use '->' instead?

These are my structures:

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

And this is my insert code, where I did use ->, so I don't understand the error I'm getting. Any help/explanation would be greatly appreciated.

struct 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) //error here
    {
        node->right = Insert(node->right, i);
    }
    else if(i.invPartNo < node->data->invPartNo) //error here
    {
        node->left = Insert(node->left, i);
    }
    return node;
}

Upvotes: 0

Views: 202

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

Type of i is inventory * so you should replace i.invPartNo with (*i).invPartNo or equivalent i->invPartNo to resolve your error.

operator . is applicable for struct objects and not pointers to struct object. Operator * dereferences the pointer and dereferenced type is same struct object enabling the use of . here. But (*i).memb is noicy, so C language syntax provide a shortcut equivalent for the same as i->mem.

Upvotes: 2

Related Questions