In the shuffleDeck function, I'm printing out "cards" in the while loop and I'm getting junk after some of the strings along with a segfault at the bottom of the list. I tried using realloc, in order to reallocate the string to the size of the new string being copied to it, but that didn't do it. Any help? Thanks.
Code:
void setCards(char **cards){
char *suit[SUIT_MAX] = {"Clubs", "Diamonds", "Hearts", "Spades"};
char *rank[RANK_MAX] = {"Ace", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "Jack", "Queen", "King"};
int rankIdx, suitIdx, cardIdx;
for(suitIdx = 0; suitIdx < SUIT_MAX; suitIdx++){
for(rankIdx = 0; rankIdx < RANK_MAX; rankIdx++){
cardIdx = suitIdx * RANK_MAX + rankIdx;
cards[cardIdx] = malloc(strlen(suit[suitIdx]) + strlen(rank[rankIdx]) + 4);
sprintf(cards[cardIdx], "%s of %s", rank[rankIdx], suit[suitIdx]);
cards[cardIdx][strlen(cards[cardIdx])] = '\0';
}
}
}
void shuffleDeck(char **cards){
int cardIdx = RANK_MAX * SUIT_MAX;
char *temp;
while(cardIdx > 1){
int random = rand() % cardIdx;
cardIdx--;
temp = malloc(strlen(cards[cardIdx]));
strcpy(temp, cards[cardIdx]);
temp[strlen(temp)] = '\0';
cards[cardIdx] = realloc(cards[cardIdx], strlen(cards[random])); <-- ??
strcpy(cards[cardIdx], cards[random]);
strcpy(cards[random], temp);
free(temp);
puts(cards[cardIdx]);
}
}