I'm trying to print out slected strings from a const char pointer array but the text displayed is absolutely garbage. I am not sure what went wrong. I condensed the code down for easy read below:
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define HAND_CARDS 5 /* maximum number of cards any particular Hand */
typedef struct card {
int suit;
int face;
} Card;
typedef struct hand {
struct card pHand[5];
int hQuality;
} Hand;
void print_pHand(struct hand player, const char* suit[], const char* face[]);
int main(void)
{
/* initialize memory arrays of suit and face, to be referenced through out the game */
const char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};
const char *face[13] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"};
int deck[4][13] = { 0 };
Hand pHuman = { 0 };
print_pHand(pHuman, suit, face);
return 0;
}
void print_pHand(struct hand player, const char* suit[], const char* face[])
{
int f = 0, s = 0, i = 0;
for (i = 0; i < HAND_CARDS; ++i) {
s = player.pHand[i].suit;
f = player.pHand[i].face;
printf("[%s : %s]\t", suit[s], face[f]);
}
}
I changed the printf() part and it still produced the same problem.
Unhandled exception at 0x79B81F4C (ucrtbased.dll) in PA7.exe:
0xC0000005: Access violation reading location 0xF485A8D3. occurred
Seems like there is memory access problem but I am not sure how to fix it.
Note: Assuming the cards have already been dealt randomly to each player, although I might have missed some important part. So for the full code, please look at my github here:
This line in your code,
printf("[%5s : %-8s%c", suit[s], face[f]);
is passing insufficient amount of arguments to printf()
. As there are three '%'
in your call, printf()
expects another three arguments, not two. However, since printf()
is implemented as a variadic function, it had no idea how many arguments you actually passed to it, so it managed to access some memory where your non-existent third argument would have occupied, causing the error.
User contributions licensed under CC BY-SA 3.0