I’m doing a orders program and I have a binary search tree for products, item contain product name, stock quantity, order quantity, and price. When I creeate an order, the order quantity in the selected item is increased according to the order.
I am required to create a function, called batchUpdate, which goes goes through the tree and substracts the stock quantity by the order quantity for each item, and obviously setting the order quantity to 0 again. The order quantity is being updated when a new order is created, but for some reason nothing is happening. here are a few snippets:
void BatchUpdate(PTree * pt) //PTree is a typedef, the tree
{
if (PTreeIsEmpty(pt))
puts("Nothing to update!");
else
{
puts("test"); //just for debug, it is still being displayed
TraverseP(pt,MinusStock); //Traverses the tree, and applies function
//MinusStock to each item in the node
}
}
void MinusStock(Prdct C) //Prdct is a typedef of struct containing details
{
C.StockQ = C.StockQ - C.OrderQ;
C.OrderQ = 0;
}
void TraverseP(const PTree * ptree, void (* pfun)(Prdct item))
{
if (ptree != NULL)
InOrderP(ptree->root,pfun);
}
static void InOrderP(const PNode * root, void (* pfun)(Prdct item))
{
if (root != NULL)
{
(*pfun)(root->item);
InOrderP(root->left, pfun);
InOrderP(root->right, pfun);
}
}
no error is being given, it just ignores the traverse, and puts(“test”) is being displayed
This is the problem, you are taking it by value, this means that any changes are NOT affecting the tree elements, since you are operating on a copy of the data which is destroyed after this function terminates.
This can be fixed by making the below change.
This means you take the product struct as a pointer and thus any changes to it are persistant.
To do this you also need to change both how you call,
(*pfun)(&root->item);and how you access the variable,C->OrderQ = 0;, and how you define the function pointer,void (* pfun)(Prdct* item).Thank you @MathewHall for correctly pointing out that this is a C question.
To summarise, the traverse IS happening, but it is not changing the tree, instead it is creating copies of each element before it operates on them, leaving the tree as-is.