C 从现有结构数组中查找并返回指向结构的指针

C 从现有结构数组中查找并返回指向结构的指针,c,pointers,struct,C,Pointers,Struct,当我试图返回一个指向一个已经存在的带有数组的结构的指针时,我遇到了一个不兼容的类型错误 以下是相关的结构定义: typedef struct cust_t* Customer; typedef struct item_t* Item; struct item_t { int id; char *label; }; struct cust_t { int id; int basket_size; Item basket; }; 如您所见,这些结构定义

当我试图返回一个指向一个已经存在的带有数组的结构的指针时,我遇到了一个不兼容的类型错误

以下是相关的结构定义:

typedef struct cust_t* Customer;
typedef struct item_t* Item;

struct item_t {
    int id;
    char *label;
};


struct cust_t {
    int id;
    int basket_size;
    Item basket;
};
如您所见,这些结构定义了一个拥有一篮子项目的客户。因此,
basket
是一个
项的数组

然后我有以下两个功能:

/*
Add data to the item with id item_id in the basket of cust
*/
void add_item_data(Customer cust, int item_id, void* data) {
    Item *v;
    v = find_item(cust, item_id);

    //Use the pointer to the item, v, and attribute data to it (unimplemented)
}

/*
Find the item with id id in the basket of cust, and return a pointer to it.

Assumes that the id of all items have been previously defined.
*/
Item *find_item(Customer cust, int id){

    Item *v;

    //Iterate over the length of basket looking for a match in the id's...
    for (int i = 0; i < cust->basket_size; i++){
        if (cust->basket[i].id == id){
            v = cust->basket[i];
            return v;
        }
    }
    //if the item is not in the basket, return null. program should not reach here
    return NULL;
} 

我猜我的指针语法在某个地方不正确,但我看不到在哪里。

v
Item*
类型的变量,即
Item\u t**

cust->basket
属于
Item
类型,即
Item\u t*
,因此任何
cust->basket[i]
都是
Item\u t

现在您正在尝试这样做:

v=cust->basket[i]

我相信错误已经很清楚了:正如错误消息所指出的,您试图将类型为
item\t
的值赋给
item\t**
变量


考虑不使用typedef来屏蔽那样的指针,这样您就可以一眼就知道变量是否是指针。

您已经将
作为指向
结构的指针键入。客户的typedef也有类似的情况。这在语义上很尴尬。
项*
可以更好地解释为项的数组,特别是指向数组中第一个项的地址的指针。如果您不熟悉数组和指针的概念,这里有一个初学者对于C++,但是在两种语言中都是相同的,唯一的C++特定部分是使用<代码> STD::CUDE EMISOR已经突出了实际问题。我只是有时间来浏览,但是我认为你已经做了一个奇怪的方式。也许TyBufff没有指针的结构,然后有CuSTyt持有一个项目*-不要使用Type Debug来“隐藏”。指针-如果有什么命名那些typedefs CustomerPtr和ItemPtr的话-原因是你在没有意识到的情况下为自己挖了一层额外的间接层。它不
typedef
指针。它混淆了语义并最终导致混淆。这是否意味着我应该将
v
转换为
(item\u t**)
或类似的东西?
v
已经是一个
项**
。相反,您可能想更改
cust
声明,因为
basket
应该是一个
项的数组,而不是
项本身。而且
v
find\u项的返回值都应该是
Item
,而不是
Item*
。至少,如果你这样做,它可能会编译,但我真的不知道这是否是你最初打算做的…@PythonNewb:只使用cast iff 1)这是绝对必要的2)您完全理解所有含义,并3)完全接受它们。@或者我不愿意更改
cust
的声明,我已经获得了构建代码的基础,不想意外地破坏代码的其他部分
error: incompatible types when assigning to type 'struct item_t **' from type 'struct item_t'
v = cust->basket[i];
Item find_item(Customer cust, int id){

    Item v;
     //snip snip
            v = &(cust->basket[i]); //using & as address-of operator here
            return v;
     //snip snip