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.