-7

I'm making a card shuffling function for the card game. I created an array of Card objects. Then I tried to rearrange the objects in the array using random_shuffle. But it doesn't work.

char faces[13] = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };
char suits[4] = { char(3), char(4), char(5), char(6) };
int values[13] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11 };

Card** deck = new Card*[52];

for (int row = 0; row <= 3; row++)
{
    for (int column = 0; column <= 12; column++)
    {
        deck[Card::getCounter()] = new Card(suits[row], faces[column], values[column], true);
    }
}
int size = sizeof(deck) / sizeof(deck[0]);
random_shuffle(*deck, *deck + size);

I mean, if I check with cout, like

 cout << deck[0]->getFace()<< deck[0]->getSuit() << endl;

it shows 2(heart), like it was before using random_shuffle

1 Answers1

1

The problem with your code is that operator size returns the size of a pointer (8 on a 64-bit machine) rather than the size of the array it points to. As a consequence, the expression

  sizeof(deck) / sizeof(deck[0])

returns 1, and you only shuffle a single value, which means you don't shuffle. The solution can be:

  1. use the explicit size of the array random_shuffle(*deck, *deck + 52);
  2. Better, define

    const int NUM_OF_CARD_IN_DECK= 52

and use it anywhere you need it

  1. Better still, use an std::vector
Ophir Gvirtzer
  • 604
  • 4
  • 8