2015-06-24 41 views
1

我無法弄清楚如何使用qsort。我想排序一個字符串數組。像這樣:在字符串數組上使用qsort

John    Adam 
Adam  ->  John 
Stacy    Stacy 

但是,沒有我做的似乎工作。我試着複製別人已經使用過的東西(大約5種來自不同來源的不同的qsort函數),而且沒有任何工作。我有一個int的工程(倒退,但至少它的作品)。

這裏是必要的代碼,我有:

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

typedef struct { 
char name[80]; 
int age; 
} RECORD; 
RECORD record[25]; 

int main (int argc, char *argv[80]){  // Using command line to get my strings 

    int i = 2, j; 
    for(j = 0; j < (argc/2); j++)  //Converting and storing my ages 
    { 
     record[j].age = atoi(argv[i]); 
     i = i + 2; 
    } 

    int p, q = 1; 
    for(p = 0; p < (argc/2); p++) 
    { 
     strcpy(record[p].name, argv[q]); 
     q = q + 2; 
    } 
} 

int compareByName(const void* a, const void* b) //The qsort that doesn't work at all 
{ 
    const char *ia = (const char *)a; 
    const char *ib = (const char *)b; 

    return strncmp(ia, ib, 25); 
} 

int compareByAge (const void * a, const void * b) //My other qsort that works backwards 
{ 

    RECORD *RECORDA = (RECORD *)a; 
    RECORD *RECORDB = (RECORD *)b; 

    return (RECORDB->age - RECORDA->age); 
} 

void printRecords(RECORD r[], int num){ 
//printing stuff here 

double size = sizeof r[0]; 
double count = sizeof(r)/size;   //My qsort with size stuff, doesn't work 
qsort(r, count, size, compareByName); // if I do it the same as the other 

qsort (r, 25, sizeof(RECORD), compareByAge); //My other qsort that works backwards 

//more printing stuff here 
} 
+0

不是說年齡可能會溢出,而是爲了避免溢出使用(RECORDB-> age> RECORDA-> age) - (RECORDB-> age < RECORDA-> age) ' – chux

回答

4

你沒有一個字符串數組,你有RECORD秒的陣列,這聽起來像你想設置基於字符串數組排序在記錄的name數組中。所以,你想是這樣的:

int compareByName(const void *a_, const void *b_) { 
    RECORD *a = a_, *b = b_; 

    return strcmp(a->name, b->name); 
} 

,然後用

qsort (r, 25, sizeof(RECORD), compareByName); 
1

好了,你的排序,我在這裏看到的幾個問題。

值得注意的是,sizeof是在編譯時評估的,因此您不能使用sizeof(r)來確定您傳遞的動態大小數組的大小。我會猜測這就是爲什麼num被傳遞到printRecords

正如@Chris所指出的,您正在排序RECORD結構而不是字符指針,所以比較函數和qsort調用都需要考慮這一點。

您在年齡比較中反轉了相減 - 如果左側小於右側,則需要返回負數,所以請使用RECORDA->age - RECORDB->age

1

首先(這是爲什麼你的字符串沒有排序),double count = sizeof(r)/size;是錯誤的。 sizeof(r)沒有達到你期望的效果。你需要數組的大小傳遞給printRecords()在這個問題描述:

How to get the length of array in C? is "sizeof" is one of the solution?

第二關, int compareByAge (const void * a, const void * b) //My other qsort that works backwards是倒退,因爲你倒着做。比較器的功能總是返回A - B,而不是B - A.

+0

謝謝,我解決了sizeof問題。當我用'RECORDA-> age - RECORDB-> age'替換'RECORDB-> age - RECORDA-> age'時,qsort完全停止工作,併爲我的打印功能提供空白數據。與我現在的工作名稱qsort一樣。如果我嘗試用正確的方式翻轉它們,則會提供空白數據。 – Rick