2015-06-24 39 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