[英]Putting a struct member inside of a separate variable to clean up code and helping me understand how the code would look formatted differently
在 C 中,不是僅僅列出一個結構變量,例如((struct listing*)p)
,我的變量應該是哪種原始類型才能保存它,它看起來如何?
例如,我目前在我的程序中有這個功能:
int price_comparator(const void* p, const void *q){
float price1 = ((struct listing*)p)->price;
float price2 = ((struct listing*)q)->price;
return (price1 - price2);
}
這確實有效,但是,我想以不同的方式格式化此函數。 我想稍微清理一下的一種方法是將 "((struct listing*)p)" 放入變量中,然后再將其放入 price1 變量中。
我想嘗試這樣的事情:
struct structOne = ((listing*)p);
要么
void structOne = ((listing*)p);
但據我所知,這兩個都不起作用。 此外,括號讓我有點困惑:
((struct listing*)q)->price
我希望看到它的格式不同,例如當它沒有指向“價格”的箭頭時,以便更清楚地了解它是如何工作的。
我的 stuct 已經在我的程序開始時創建如下:
struct listing {
float latitude, longitude, price;
};
但這不需要回答我的問題
謝謝!
您可以使用pointers to structure
的void pointers
而不是void pointers
:
int price_comparator (struct listing *p, struct listing *q)
{
return (p->price - q->price);
}
據我了解,您希望在不使用箭頭的情況下訪問結構以及要使用的數據類型。
第一:你的數據類型應該是 struct listing * 而不是 void * 類型。
第二:為了使打字更容易,你應該使用 typedef 聲明你的結構
typedef struct {
float latitude, longitude, price;
} listing;
這將使您的結構更容易使用,而不是使用:
struct listing x = {2.3, 3.5, 11.0};
你可以這樣做:
listing x = {2.3, 3.6, 11.5};
第三:要在沒有 void * 箭頭的情況下訪問指向 struct 的指針,您可以這樣做:
float price1 = (*((listing *) p)).price;
float price2 = (*((listing *) q)).price;
return price1 - price2;
我希望回答了你的問題。
您可以制作正確類型的本地指針:
int price_comparator(const void* p, const void *q)
{
struct listing const *p1 = p;
struct listing const *q1 = q;
return p1->price - q1->price;
}
這里不需要強制轉換,因為我們已經為 p1 和 q1 指定了類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.