配列を持つ既存の構造体へのポインタを返そうとすると、互換性のない型エラーが発生します。ここで既存の構造体の配列から構造体へのポインタを検索して返します
は、関連する構造の定義です:
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
はItem
の配列です。
は、私はその後、以下の2つの機能を持っている:
/*
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;
}
あなたは第二の機能は、バスケットは、すでに自分のIDがすでに設定されていた、すでにそこにあるアイテムの数を持っていることを前提として見ることができます。 void* data
には、label
などの情報が含まれます。
私の問題は、私はそれがそうadd_item_data
はそれを使用することができ、basket
に既存のItem
構造体へのポインタを返すようにしたい、find_item
機能です。
私はコンパイルするとき、私は次のエラーを取得する:
error: incompatible types when assigning to type 'struct item_t **' from type 'struct item_t'
v = cust->basket[i];
私は私のポインタの構文を推測しているが、どこかオフになっているが、私は場所を確認することはできません。
Emisorは実際の問題点を強調しています。私はスキミングする時間がありますが、あなたはこれを奇妙な方法でやったと思います。ポインタを持たない構造体をtypedefし、cust_tにItemを保持させる* - ポインタを隠すためにtypedefを使用しない - これらのtypedefに名前をつけた場合CustomerPtrとItemPtr - それを実現する –
ポインタを 'typedef'しないでください。それは意味論を難読化し、最終的には混乱を招く。 – Olaf