简体   繁体   English

在C中对结构数组进行排序

[英]Sorting a array of structs in C

I have a array of struct, which I wish to sort in ascending order. 我有一个结构体数组,希望以升序排序。

After quite a lot of research on Stack Overflow, I found sorting members of structure array . 在对Stack Overflow进行了大量研究之后,我发现了对structure array的排序成员

Therefore I have the following code: 因此,我有以下代码:

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

typedef struct StockItem {
    int unitPrice;
    // ...
} stockItem;

int comparePrice(const void* a, const void* b)
{
    stockItem *stockItem1 = (stockItem *) a;
    stockItem *stockItem2 = (stockItem *) b;
    return stockItem1->unitPrice - stockItem2->unitPrice;
}

int main() {
    stockItem stockItem1;
    stockItem1.unitPrice = 15;

    stockItem stockItem2;
    stockItem2.unitPrice = 41;

    stockItem stockItem3;
    stockItem3.unitPrice = 25;

    stockItem stockItems[3] = {stockItem1, stockItem2, stockItem3};
    int size = 3;

    qsort(stockItems, (size_t) size, sizeof(int), comparePrice);

    printf("\n");
    for (int i = 0; i < size; i++) {
        printf("%d\n", stockItems[i].unitPrice);
    }

    return 0;
}

However, this doesn't seem to sort the array. 但是,这似乎没有对数组进行排序。

That's weird. 这很奇怪。 The only thing I can see is that you should be using sizeof(stockItem) , not int, but that shouldn't matter unless your system has weird alignment. 我唯一能看到的是您应该使用sizeof(stockItem) ,而不是int,但这没关系,除非您的系统具有奇怪的对齐方式。 Also the cast to size_t on size isn't necessary, but that definitely doesn't matter. 同样,不必将大小强制转换为size_t,但这绝对无关紧要。

Edit: I tried to add a link to the code working online, but it I'm bad links. 编辑:我试图添加一个链接到在线工作的代码,但它是错误的链接。 Basically, the struct alignment isn't guaranteed unless you use packing. 基本上,除非使用打包,否则不能保证结构对齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM