我正在编写一个二叉树程序,其中树中的每个节点都包含一个结构。 我坚持如何正确地输入结构以打印它的内容。
这是我的结构定义:
//inventory definition
typedef struct inventory
{
char invName[36];
int invPartNo;
int invQOH;
float invUnitCost;
float invPrice;
}item;
//tree definition
struct btree {
void *data;
struct btree *left;
struct btree *right;
} ;
在这里,我尝试输入转换结构内容,以便打印出来:
void print_inorder(btree *node)
{
if(node == NULL)
{
return;
}
print_inorder((struct btree*)node->left);
//error here in these 5 lines: the node->data->invName, invPartNo, etc.
printf("Name: %s\n", (char)node->data->invName); //my incorrect attempt
printf("Part Number: %.5d\n", (int*)node->data->invPartNo);
printf("Quantity on hand: %d\n", node->data->invQOH);
printf("Unit Cost: %0.2f\n", node->data->invUnitCost);
printf("Price %0.2f\n\n", node->data->invPrice);
print_inorder(node->right);
}
答案 0 :(得分:0)
我可以假设你有编译错误。
不要犹豫使用更多括号而忘记将void*
投射到item*
:
printf("Name: %s\n", ((item*)(node->data))->invName);
printf("Part Number: %.5d\n", ((item*)(node->data))->invPartNo);
printf("Quantity on hand: %d\n", ((item*)(node->data))->invQOH);
printf("Unit Cost: %0.2f\n", ((item*)(node->data))->invUnitCost);
printf("Price %0.2f\n\n", ((item*)(node->data))->invPrice);
答案 1 :(得分:0)
在void
- 指针:
item * pitem = node->data;
测试它是否指向某物并打印出来:
if (NULL != pitem)
{
printf("Name: %s\n", pitem->invName);
printf("Part Number: %.5d\n", pitem->invPartNo);
printf("Quantity on hand: %d\n", pitem->invQOH);
printf("Unit Cost: %0.2f\n", pitem->invUnitCost);
printf("Price %0.2f\n\n", pitem->invPrice);
}
或断言是否无效:
assert(NULL != pitem);
printf("Name: %s\n", pitem->invName);
printf("Part Number: %.5d\n", pitem->invPartNo);
printf("Quantity on hand: %d\n", pitem->invQOH);
printf("Unit Cost: %0.2f\n", pitem->invUnitCost);
printf("Price %0.2f\n\n", pitem->invPrice);