我有一個指向Objective-C對象的指針數組。這些對象有一個與它們相關的排序鍵。我試圖使用qsort來排序這些對象的指針數組。但是,第一次調用比較器時,第一個參數指向數組中的第一個元素,但第二個參數指向垃圾,當我嘗試訪問其排序鍵時,給了我一個EXC_BAD_ACCESS。在指向Objective-C對象的指針數組上的qsort
這裏是我的代碼(轉述):
- (void)foo:(int)numThingies {
Thingie **array;
array = malloc(sizeof(deck[0])*numThingies);
for(int i = 0; i < numThingies; i++) {
array[i] = [[Thingie alloc] initWithSortKey:(float)random()/RAND_MAX];
}
qsort(array[0], numThingies, sizeof(array[0]), thingieCmp);
}
int thingieCmp(const void *a, const void *b) {
const Thingie *ia = (const Thingie *)a;
const Thingie *ib = (const Thingie *)b;
if (ia.sortKey > ib.sortKey) return 1; //ib point to garbage, so ib.sortKey produces the EXC_BAD_ACCESS
else return -1;
}
任何想法,爲什麼發生這種情況?
你是否檢查'b'是否指向分配數組內?也許這將提供一個線索。 – 2010-04-02 01:04:54
爲什麼不使用NSArray或類似的可可數據結構來跟蹤你的Thingies並對它們進行分類? – stefanB 2010-04-02 02:13:51
不幸的是,NSArray在這個*特殊情況下不符合我的要求。看到我對下面的bbum(優秀)答案的迴應。 – ElBueno 2010-04-02 09:58:59