Qsort删除元素

时间:2018-01-27 22:34:15

标签: c qsort

我正在尝试使用qsort对结构数组进行排序,但是当我显示已排序的结构时,除了一个缺失之外。

以下是我的代码的相关部分:

typedef struct {
    char firstName[20];
    char lastName[20];
    float height;
} myStruct;

...

 else if (argc > 2) {
            FILE * inf;
            inf = fopen(argv[2], "r");
            errorCheck(fscanf(inf, "%d", &numStructs));
            people = (myStruct*)malloc(sizeof(myStruct) * numStructs);
            for (int i = 0; i < numStructs; ++i) {
                    errorCheck(fscanf(inf, "%s %s %f", firstName, lastName, &height));
                    person = people + (sizeof(myStruct) * i);
                    initMyStruct(person, firstName, lastName, height);
            }
            printf("struct read in");
    }

...

    if (strcmp(argv[1], "last") == 0) {
            fprintf(stdout, "last name sort if statement, \n");
            //myStruct* person = people + (sizeof(myStruct));
            qsort(people, numStructs, sizeof(myStruct), lastCmp);
    }
    else {
            fprintf(stdout, "height sort if statement, \n");
            //myStruct* person = people + (sizeof(myStruct));
            qsort(people, numStructs, sizeof(myStruct), heightCmp);
    }

和我的比较函数

int lastCmp(const void *a, const void *b) {
        myStruct* c = (myStruct *)a;
        myStruct* d = (myStruct *)b;
        return(strcmp(c->lastName, d->lastName));
}

int heightCmp(const void* a, const void* b) {
        myStruct *personA = (myStruct *)a;
        myStruct *personB = (myStruct *)b;
        return((personA->height > personB->height) - (personB->height > personA->height));
}

这是输出:

First name: Abigail, last name: Egan, height: 5.300000, 
First name: Jim, last name: Gardner, height: 5.500000,
First name: Jenna, last name: Adams, height: 5.500000,
First name: Maggie, last name: Johnson, height: 4.900000,
First name: Chelsea, last name: Harrison, height: 5.400000,
First name: Anna, last name: DeHart, height: 5.000000,

First name: , last name: , height: 0.000000,
First name: , last name: , height: 0.000000,
First name: , last name: , height: 0.000000,
First name: , last name: , height: 0.000000,
First name: , last name: , height: 0.000000,
First name: Abigail, last name: Egan, height: 5.300000,

(我对可读性表示道歉,格式化不存在。)如果您需要查看我的代码的其他部分,请告诉我。第一个输出是读取后立即的结构数组。第二个是排序后的结构。我需要继续使用qsort,我不能使用不同的方法。

1 个答案:

答案 0 :(得分:0)

您的问题无法可靠地分析,因为您没有发布实际源代码以获得最小,完整且可验证的示例。你还需要发布输入到程序的输入。

我会冒险对观察到的行为进行解释:

  • 您对fscanf()成功的测试不正确:针对EOF的测试不充分,您必须检查fscanf()转换了3个输入并返回3。输入错误将导致fscanf()返回短计数,后续调用将忽略输入,使变量处于不一致状态。

  • 错误输入例如Michael J Fox 5.2:firstName将获得Michael,lastName将获得J,而height的转换将失败。后续调用将使输入流不同步...