【发布时间】:2015-06-24 03:19:36
【问题描述】:
我不知道如何使用 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)