In a do-while loop a new card must be drawn until it doesn't satisfy the requirements.When the card is "A Spade" we should add it to the deck and just stop drawing random cards.Sometimes the output finishes with "A Spade", but sometimes it is some different card type.I believe there is something wrong with the code.
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
const char const available_values[13] =
{
'2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'
};
const char* const available_paints[4] =
{
"club", "diamond", "heart", "spade"
};
typedef struct card_t
{
char value;
char* paint;
} Card;
void initialize_card(Card* card)
{
int value_index = rand() % 13;
int paint_index = rand() % 4;
card->value = available_values[value_index];
card->paint = available_paints[paint_index];
}
Card* card_draw()
{
Card card;
initialize_card(&card);
return &card;
}
int main() {
srand((unsigned int)time(NULL));
unsigned count = 0;
Card* card;
Card* old_deck = NULL;
Card* new_deck;
do {
new_deck = old_deck;
count++;
old_deck = calloc(count, sizeof(Card));
if (!old_deck) {
printf("Memory allocation error");
break;
}
for (unsigned i = 0; i < count-1; i++) {
old_deck[i] = new_deck[i];
free(new_deck);
}
card = card_draw();
old_deck[count-1] = *card;
printf("%c %s\n\n", card->value, card->paint);
} while (card->value != 'A' && card->paint != "Spade");
return 0;
}
New version:
Constant.h: https://pastebin.com/av9pBabk
Main.cpp: https://pastebin.com/jJttNWjj
I hope it could be useful, thank you all!