我無法弄清楚如何使用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
}
不是說年齡可能會溢出,而是爲了避免溢出使用(RECORDB-> age> RECORDA-> age) - (RECORDB-> age < RECORDA-> age) ' – chux