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.

3
  • 1
    What output do you get? Commented Mar 27, 2016 at 2:17
  • What is sizeof(int) and sizeof(stockItem)? Commented Mar 27, 2016 at 2:27
  • It just returned the same array, with no changes Commented Mar 27, 2016 at 15:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This should be a comment.
That's actually the answer! Try rewording your post to be more suited as an answer. I used sizeof(int), where I should have used sizeof(stockItem).
Yes it should, I posted too early because I have fat fingers on mobile
And now mobile is stripping my links, I give up, link is: http: // goo.gl/ZWwzh0
And the reason it worked online, is because the struct is actually larger. I just used a smaller version. Editing question now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.