Reputation: 1
I'm writing a function that is given a deck of cards and a card to check if it contains in said deck.
Function names and structs were given to me and i cannot change it.
My code looks like this after some modifications:
int deck_contains(deck_t * d, card_t c) { //for this snippet I was given the function name and wrote the body
for(int i = 0; i < d->n_cards; i++) {
if(c == (*(*d->cards))'){
return 1;
}
}
return 0;
}
Struct deck_t like this:
**struct deck_tag {
card_t ** cards;
size_t n_cards;
};
typedef struct deck_tag deck_t;**
Struct card_t like this:
struct card_tag {
unsigned value;
suit_t suit;
};
typedef struct card_tag card_t;
Now the thing is that when i try to compile the code I receive this error message:
cc -ggdb3 -Wall -Werror -pedantic -std=gnu99 -c -o deck.o deck.c
deck.c: In function ‘deck_contains’:
deck.c:17:10: error: invalid operands to binary == (have ‘card_t’ {aka ‘struct card_tag’} and
‘card_t’ {aka ‘struct card_tag’})
17 | if(c == (*(*d->cards))){
| ^~ ~~~~~~~~~~~~~~
| |
| card_t {aka struct card_tag}
make: *** [<builtin>: deck.o] Error 1
Upvotes: 0
Views: 79
Reputation: 67476
example code:
typedef enum
{
S,H,C,D,
}suit_t;
typedef struct card_tag
{
unsigned value;
suit_t suit;
}card_t;
typedef struct deck_tag
{
size_t n_cards;
card_t cards[];
}deck_t;
deck_t *allocate(const size_t ncards)
{
deck_t *deck = malloc(sizeof(*deck) + ncards * sizeof(deck -> cards[0]));
if(deck)
{
deck -> n_cards = ncards;
/* some other code */
}
return deck;
}
int deck_contains(const deck_t *d, const card_t c)
{
int result = 0;
if(d)
{
for(size_t i = 0; i < d -> n_cards; i++)
{
if(d -> cards[i].value == c.value && d -> cards[i].suit == c.suit)
{
result = 1;
break;
}
}
}
return result;
}
Upvotes: 1
Reputation: 222660
C will not automatically compare structures with ==
.
You can compare two structures by comparing all of their members.
You can compare structures by using memcmp
, but this may falsely indicate that two structure differ if they contain padding bytes, and the contents of the padding bytes differ in the structures. In situations where you know there is no padding in a structure, memcmp
could be used.
Additionally, *(*d->cards))
refers to only the first card in the deck. Change if(c == (*(*d->cards))')
to if (c.value == (*d->cards)[i].value && c.suit == (*d->cards)[i].suit)
. (I presume the stray '
was some copy-and-paste error.)
Upvotes: 0