Reputation: 306
typedef struct {
char* value;
char* type;
} CARD;
CARD cards[52];
void initializeCards() {
char* types[10] = {"Spade", "Club", "Hearts", "Diamonds"};
char* values[13] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "B", "D", "K"};
shuffleArray(&values, 4); //I've also tried *values, or just values
for (int i = 0; i < 4; i++) {
for (int e = 0; e < 13; e++) {
cards[i*13 + e].type = types[i];
cards[i*13 + e].value = values[e];
}
}
}//initializeCards.
//Code in this function comes from this thread: https://stackoverflow.com/questions/34844003/changing-array-inside-function-in-c
//I've tried many different things inside this function, none of these seem to work.
void shuffleArray(char** array, uint8_t size) {
free(*array);
*array = malloc(size * sizeof(int));
//char* temp = (*array)[0];
//(*array)[0] = 1;
(*array)[0] = "test";
printf("%s\n", &array[0]);
}//shuffleArray.
I'm trying to get a deck of cards into an array, these cards should be shuffled, but instead of shuffling the array with the cards, I want to shuffle these 2 shorter arrays 'values' and 'types', because they are shorter and thus take fewer iterations to shuffle.
I've tried many different things none of them worked, What I wanted is to change the pointers of the array in the function 'shuffleArray' so that the array in the other function automatically changes as well.
if any of you could help me do the following correctly, I think I'll manage in shuffling them completely:
//This is pseudo-code, if I get this correctly I should be able to shuffle them.
temp = array[0]
array[0] = array[size-1]
array[size-1] = temp
Upvotes: 0
Views: 125
Reputation: 212248
It's not entirely clear what you're trying to do, but you certainly cannot free
an array that is not allocated via malloc (and family). Perhaps you want something like:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <assert.h>
struct card {
char *value;
char *suit;
};
struct card cards[52];
void initializeCards(void);
void shuffleArray(char **, size_t);
int
main(void)
{
srand(time(NULL));
initializeCards();
for( int i = 0; i < 52; i++ ){
printf("%s of %s\n", cards[i].value, cards[i].suit);
}
}
void
initializeCards(void)
{
char *suits[] = { "Spades", "Clubs", "Hearts", "Diamonds" };
char *values[] = {
"Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"
};
shuffleArray(values, sizeof values / sizeof *values);
shuffleArray(suits, sizeof suits / sizeof *suits);
struct card *c = cards;
for(unsigned i = 0; i < sizeof suits / sizeof *suits; i++ ){
for( unsigned e = 0; e < sizeof values / sizeof *values; e++ ){
assert( c < cards + sizeof cards / sizeof *cards );
c->suit = suits[i];
c->value = values[e];
c += 1;
}
}
}
void
shuffleArray(char **array, size_t n)
{
for( unsigned i = 0; i < n - 1; i++ ){
unsigned j = i + rand() % (n - i);
char *t = array[i];
array[i] = array[j];;
array[j] = t;
}
}
Upvotes: 2