I'm creating two struct's: Deck and Card. I want sort the cards of the deck using qsort but this is not working. When I run an exception occurs: Segmentation fault. Follow my code:
typedef struct Card {
int value;
}Card;
typedef struct Deck{
Card *c[100];
int top;
}Deck;
Card * newCard(int value) {
Card * aux = (Card *)malloc(sizeof(Card));
aux->value = value;
return aux;
}
Deck * newDeck() {
Deck * deck = (Deck *)malloc(sizeof(Deck));
deck->top = 0;
return deck;
}
void addCard(Deck *b, Card *c) {
b->top++;
b->c[b->top] = c;
}
int compare(const void *x, const void *y) {
Card * xa = *(Card **) x;
Card * ya = *(Card **) y;
if(xa->value == ya->value)
return 0;
if(xa->value > ya->value)
return 1;
return -1;
}
void sort(Deck *b) {
qsort(b->c, b->top, sizeof(struct Card*), compare);
}
int main() {
Deck * b = newDeck();
addCard(b,newCard(11));
addCard(b,newCard(12));
addCard(b,newCard(11));
addCard(b,newCard(1));
addCard(b,newCard(1));
sort(b);
return 0;
}
Someone can help me? I just want sort the cards of the deck but something is wrong with the logic. Probably something like pointer(malloc or calloc?).
CardinDeckwithout allocating it....b->top++; b->c[b->top] = c;Increase the variable after adding, not before.