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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Nov 25 '17 at 02:29

1 Answers1

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;
lamandy
  • 962
  • 1
  • 5
  • 13
  • Good references are [Fisher Yates shuffling algorithm in C](https://stackoverflow.com/questions/42321370/fisher-yates-shuffling-algorithm-in-c) and see the link to the original SO question in the answer. – David C. Rankin Nov 25 '17 at 05:04