[英]Retrieving struct from array of struct in C for qsort
我正在嘗試從結構數組中的結構中檢索兩個值,但是我不知道自己在做什么錯。 我需要這個qsort 。
這是我的代碼示例:
typedef struct test {
int data1;
int data2;
} *test;
然后我制作一個struct數組,並返回一個指向該數組的指針:
test* foo(**some args**)
test* array = malloc(sizeof(proc));
int currentElement = 0;
while(...){
// get some data
// and make space for struct
array[currentElement] = malloc(sizeof(struct test));
// add data to struct
array[currentElement] -> data1 = ...;
array[currentElement] -> data2 = ...;
// resize array for the next wave of structs
array = realloc(array, (currentElement + 1) * sizeof(struct proces));
currentElement++;
}
return array
當我嘗試訪問並打印數組中的結構時,它可以工作(numberOfElement是全局變量):
void printData(test* a) {
printf("%s\n", "Data");
int i;
for (i = 0; i < numberOfElements; i++) {
printf("%5d\n",
a[i]->data1
);
}
}
但是,如果我嘗試為qsort編寫一個編譯器函數,則會給我一個錯誤(請求成員“ data1”而不是結構或聯合):
int comp (test* first, test* second){
return first->data1 - second->data1;
}
編輯 :添加函數foo返回指向結構數組的指針。 謝謝dasblinkenlight!
我還有另一個問題:
這可行!
int comp (void *a, void* b){
test* first = (test*)a;
test* second = (test*)b;
return (*first)->data1 - (*second)->data1;
}
當我嘗試對數組進行排序時:
test* a = foo(...);
qsort(a, numberOfElements, sizeof(test), comp);
printData(a);
它給我一個錯誤:
warning: passing argument 4 of ‘qsort’ from incompatible pointer type [enabled by default]
In file included from Naloga2.c:2:0:
/usr/include/stdlib.h:765:13: note: expected ‘__compar_fn_t’ but argument is of type ‘int (*)(void *, void *)’
extern void qsort (void *__base, size_t __nmemb, size_t __size,
編輯2 :最終解決方案
int comp (const void *a, const void* b){
test* first = (test*)a;
test* second = (test*)b;
return (*first)->data1 - (*second)->data1;
}
問題是您的typedef
將test
定義為指針類型,而不是普通類型。 然后test*
成為雙指針,即struct test**
。 當您編寫first->data1
,您將->
運算符應用於指向struct test
的指針,而不是指向struct
的指針。
由於test*
是雙指針,因此您需要重寫comp
使其取消引用一次,然后才能獲取成員,如下所示:
int comp (const void *a, const void* b){
const test* first = (const test*)a;
const test* second = (const test*)b;
return (*first)->data1 - (*second)->data1;
}
您需要在內部傳遞void*
並強制轉換為test*
,因為qsort
需要一個函數指針,該函數指針需要一對恆定的void
指針。 簡單地轉換一個函數指針將可以編譯甚至可以工作,但是行為是不確定的。
typedef struct test *test;
這也可以寫成
typedef struct test* test;
因此,現在測試已經是一個指針。 所以當你寫
test *first;
它成為了
struct test **first;
你應該有類似的東西
typedef struct test test;
然后
test *first ;
first
將具有指向您的結構的指針。
這樣可以確保參數comp()
期望的是單個指針,並且訪問保持良好。
first->data1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.