2015-03-25 43 views
0

快速排序我有這樣的結構:問題在C

typedef struct item{ 
    char label[10]; 
    int support; 
}; 

我創造了這樣的結構是這樣的數組:

struct item* finstr = (struct item*)malloc(sizeof(struct item)*10); 

我充滿了適當的值數組,並要排序該數組根據'support'的值使用qsort函數。但是,數組根本沒有被分類。輸出結果與輸入相同。

這裏是調用qsort函數併爲「比較」函數的代碼:

qsort((void*)finstr,(sizeof(finstr)/sizeof(finstr[0])),sizeof(finstr[0]),comparator); 

比較功能:

int comparator(const void* i1,const void* i2) { 
    int l = ((struct item*)i1)->support; 
    int r = ((struct item*)i2)->support; 
    return l-r; 
} 

在那裏我做了錯誤,我不明白。任何幫助是極大的讚賞。

在此先感謝。

+0

'sizeof(finstr)'是指針'finstr'的​​大小,而不是指針所引用的內存量。 – 2015-03-25 06:34:45

+0

此外,第一個typedef不應該編譯imo(它缺少名稱) – a3f 2015-03-25 06:36:34

+0

http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – 2015-03-25 06:38:33

回答

1

表達式(sizeof(finstr)/sizeof(finstr[0]))不會給出元素的數量,除非finstr是一個數組。在你的情況下,它的計算結果爲sizeof(void*)/sizeof(struct item),這很可能是0

將其替換爲10

從@ForhadAhmed

優秀建議:

其良好做法,以取代malloc(sizeof(struct item)*10)10並傳遞給qsort功能與宏或變量,這樣你就不會意外調用數組的大小qsort用不同於你想要的大小的陣列。

+1

在malloc(sizeof(struct item)* 10)中取代'10'的好習慣,以及用宏或變量傳遞給qsort函數的數組大小這樣你就不會無意中調用一個與你想要的不同大小的數組 – 2015-03-25 06:38:27

0

嘗試建立並運行以下命令,看看有什麼答案你:

#include <stdio.h> 
#include <stdlib.h> 

typedef struct { 
    char bar[123]; 
    int baz; 
} foo; 

int main(int argc, char** argv) { 
    foo *foo_ptr = malloc(sizeof(foo) * 1000); 
    fprintf(stdout, "%zu\n", sizeof(foo_ptr)); 
    fprintf(stdout, "%zu\n", sizeof(foo_ptr[0])); 
    free(foo_ptr); 
    return 0; 
} 

根據架構,您可能會注意到sizeof(foo_ptr)是八個字節 - 的foo指針稱爲foo_ptr的大小。將其與sizeof(foo_ptr[0])的值進行比較。這應該提供什麼是錯誤的暗示。