Reputation: 13
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?).
Upvotes: 0
Views: 64
Reputation: 9173
Hm....Your code seems like "fill in the blanks" since you have not posted your complete code and the code that you have posted is correct. So I completed your code in a way it works:
#include <stdio.h>
#include <stdlib.h>
// Your code
typedef struct Card {
int value;
}Card;
typedef struct Deck{
Card *c[100];
int top;
}Deck;
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);
}
// My main
int main() {
Deck d;
d.c[0] = calloc(1, sizeof(Card));
d.c[0]->value = 5;
d.c[1] = calloc(1, sizeof(Card));
d.c[1]->value = 1;
d.c[2] = calloc(1, sizeof(Card));
d.c[2]->value = 3;
d.top = 3;
sort(&d);
printf("%d %d %d", d.c[0]->value, d.c[1]->value, d.c[2]->value);
return 0;
}
My guess in your segmentation fault is that you are accessing Card
without allocating it.
Update:
your addCard()
is incorrect. Here is correct one:
void addCard(Deck *b, Card *c) {
b->c[b->top] = c;
b->top++;
}
When you are adding cards, your top
points place that you need to add card. So you need to increase it after adding. Just remember that you need to add checks for it too to prevent overflowing Deck->c
.
Upvotes: 2