EDIT: Literally 1 second after I pressed the post button I got an idea and thats what it was. Why does that always happen? xD
The solution was that my player_hand[] and dealer_hand[] arrays had a size of DECK_SIZE / 2, but I was initialising them to 0 from within the for loop where I was initialising the deck[] array (which has a size of DECK_SIZE), so the last 24 0s of one of those where overflowing into deck[]...
Hello everyone!
I am trying to make a simple blackjack (21) game in C, to practice some pointer stuff, and I am running into an issue with the function that initialises all my arrays. The way I am going about setting everything up, I have an integer array for a standard deck of 52 cards (values from 1 to 13, each 4 times), an integer array for the shuffled deck, and 2 more arrays for the player and dealer hands (irrelevant at this point as they are not used yet).
My issue is that after successfully initialising the deck array (the non-shuffled one) and outputting the values from within the for loop that sets them, I get what I expect to see which is:
1, 2, 3, ..., 13, 1, 2, 3, ..., 13, ... (so on for 52 cards).
But when I output each value from a different for loop in the same function, the first 24 elements (0-23) are 0s each time I run it. I can not figure out why that would be. I ran my program through valgrind which reported that there were no memory leaks.
Here is the relevant code:
#define DECK_SIZE 52
int initialise_decks(int* deck, int* shuffled_deck, int* player_hand, int* dealer_hand, int size)
{
printf("=================INITIALISING==================\n");
for (int i = 0; i < size; i++)
{
deck[i] = (i % 13) + 1;
player_hand[i] = 0;
dealer_hand[i] = 0;
printf("deck[%d]: %d\n", i, deck[i]);
}
printf("+++++++++++++++++++++++++++++++++++++++\n");
for (int i = 0; i < size; i++)
{
printf("deck[%d]: %d\n", i, deck[i]);
}
printf("+++++++++++++++++++++++++++++++++++++++\n");
return INITIALISE_DECKS_SUCCESS;
}
int main() {
srand(time(0));
int deck[DECK_SIZE];
int shuffled_deck[DECK_SIZE];
int player_hand[DECK_SIZE / 2];
int dealer_hand[DECK_SIZE / 2];
int initialise_status = initialise_decks(deck, shuffled_deck, player_hand, dealer_hand, DECK_SIZE);
if (initialise_status != INITIALISE_DECKS_SUCCESS)
{
return INITILIASE_DECKS_FAIL;
}
return PROCESS_EXIT_NORMAL;
}
If you need to try it out for yourself here is the link to the github repo
player_hand and dealer_hand are only [DECK_SIZE/2] in length, but in initialize_decks you write zeros into them unti [DECK_SIZE -1]. Since the arrays are located next to each other in memory you end up overwriting the deck array.