0
enum rarity
{
    common,
    uncommon,
    rare,
    mythic
};

struct card
{
    unsigned int id;
    char* name;
    char* cost;
    unsigned int converted_cost;
    char* type;
    char* text;
    char* stats;
    enum rarity rarity;
} card_t ;

I have 4 entries in my card struct. For example, card[0]->name = "Stolen by the Fae", card[1]->name = "Eternal Isolation", card[2]->name = "Corpse Knight", card[3]->name = "Orzhov Enforcer".

qsort(cards, cardsaccum , sizeof(char), cmpname);

In my qsort(), I think I'm putting in the correct parameters. My cardsaccum = 4, sizeof(char) is set because I'm checking the size of the name, then calling cmpname which sorts the names in order.

int cmpname (const void *pa, const void *pb) {
const card_t *p1 = pa;
const card_t *p2 = pb;
return strcmp(p1->name, p2->name);}

After the qsort(), my sorted entries are only the last entry read which is Orzhov Enforcer.

I don't understand why this is happening and was wondering if anyone could help explain why this is happening. Below is some of my code to better follow what I'm doing.

1
  • 1
    I'm not going to read all that code. It cannot possibly all be relevant. Instead, please explain to us why you are passing sizeof(char) to qsort. What is your logic there? Commented Feb 25, 2021 at 0:57

1 Answer 1

1
qsort(cards, cardsaccum , sizeof(char), cmpname);

cards is of type card_t **, so each entry of the array is a card_t *. It's not an array of char. Thus the third argument to qsort, which specifies the size of each array element, should be sizeof(card_t *), not sizeof(char).

You could also use sizeof(cards[0]) or sizeof(*cards) to have the compiler deduce the type from the type of cards.

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

2 Comments

I would like to add that I don't understand why cards is of type card_t ** and not card_t * in this program (and everything relevant rewritten of course). Saves all kinds of unnecessary allocations.
@Cheatah: It makes the qsort a little more efficient, since each of its swaps only needs to swap two pointers instead of two of the larger card_t structures. Probably not worth the complexity and memory overhead, though.

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.