0

I need help with my function, this is what I have done.

void ShuffleCards(int (*deck_of_cards)[NUM_CARDS])
{

    int i = 51;
    int j, temp;
    while(i>0)
    {
        j = rand()%(i+1);
        temp = *deck_of_cards[i];
        *deck_of_cards[i] = *deck_of_cards[j];
        *deck_of_cards[j] = temp;
        i--;
    }
}

I have been getting segmentation fault because I'm unsure of what has to be coded properly before the swapping occurs. Help me please.

1

1 Answer 1

1

I suppose you are having an array of int used to represent a deck of card and you want to shuffle that array. First, you don't specify array size within the deck. Assuming NUM_CARDS = 52,

void ShuffleCards(int *deck_of_cards)
{
    int i = NUM_CARDS - 1; //it is better to initialize i in term of NUM_CARDS
    int j, temp;
    while(i>0)
    {
        j = rand()%(i+1); //gives 0 to i
        temp = deck_of_cards[i];
        deck_of_cards[i] = deck_of_cards[j];
        deck_of_cards[j] = temp;
        i--;
    }
}

Your calling function should look something like this:

int deck_of_cards[NUM_CARDS];

//do something to initialize your deck

ShuffleCards(deck_of_cards);

//do something with the shuffled deck;
Sign up to request clarification or add additional context in comments.

1 Comment

Good references are Fisher Yates shuffling algorithm in C and see the link to the original SO question in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.