YaoMing Su
YaoMing Su

Reputation: 11

How to swap elements in an array of pointers

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.

Upvotes: 0

Views: 319

Answers (1)

lamandy
lamandy

Reputation: 982

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;

Upvotes: 1

Related Questions