typedef struct item
{
char itemName[32];
float price;
int quantity;
}ITEM;
typedef struct list
{
void* item[5];
int (*compare)(void*, void*);
int length;
}LIST;
typedef struct order
{
int orderId;
float orderTotal;
LIST* orderItems;
int length;
} ORDER;
int compareItemPrice(void* p1, void* p2){
ITEM* p = (ITEM*)p1;
ITEM* q = (ITEM*)p2;
if(p->price>q->price)
{
return 1;
} else if(p->price<q->price)
{
return -1;
} else {
return 0;
}
}
上面的代码是我用C语言编写的结构和函数。当我实现下面的代码时,它显示了错误。错误全部与ITEM * p有关,这是结构列表的不完整定义。
ITEM* getExpensiveItem(ORDER* o){ // Maximum item price
ITEM* p = o->orderItems->item;
ITEM* expensiveItem = p;
for(int i=1; i<o->orderItems->length-1; i++)
{
if(compareItemPrice(p, (p+i)) < 0)
{
expensiveItem = p+i;
}
}
return expensiveItem;
}
答案 0 :(得分:2)
类似的代码
struct a
{
int i;
} A;
将给出一个变量A
,您可以像这样使用
A.i = 42;
但是,看来您确实是在尝试创建一种新类型。因此,尝试:
typedef struct a // Notice the "typedef" in start of line
{
int i;
} A;
这将提供类型A
,该类型可以像这样使用:
A var;
A* pVar;
var.i = 42;
pVar = &var;
....
还要注意,您的struct order
使用的类型为LIST
。因此,LIST
必须在struct order
之前声明。此外,还必须声明类型CUSTOMER
,当前它不是当前类型。
所以您的代码可能应该像这样:
#define N 42 // Made this up as it isn't in your code
typedef struct customer // Made this up as it isn't in your code
{
int x;
} CUSTOMER;
typedef struct list
{
void* item[N];
int (*compare)(void*, void*);
int length;
}LIST;
typedef struct order
{
int orderId;
float orderTotal;
LIST* orderItems;
CUSTOMER* customer;
int length;
} ORDER;
typedef struct item
{
char itemName[32];
float price;
int quantity;
}ITEM;
还要注意这一行有问题:
ITEM* p = o->orderItems->item;
由于o->orderItems->item
中的void* item[N];
,struct list
的类型为空指针数组。换句话说:您试图将一个指针数组分配给单个指针。我不太确定您想做什么,但也许像这样:
ITEM* p = o->orderItems->item[0];