1

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.

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.

Community
  • 1
  • 1
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

1 Answers1

4

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. Also the cast to size_t on size isn't necessary, but that definitely doesn't matter.

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.

Adam Martin
  • 1,188
  • 1
  • 11
  • 24