How to change an array with a function?

Go To StackoverFlow.com

3

I'm quite new to C++ and I've ran across a problem.
I'm trying to write a game of Blackjack. I have an array of size 52 of type 'char' with the different cards and I want to shuffle it. I'm not sure how but that's not the problem. I made a function called 'ShuffleDeck' but it doesn't work, says it can't return an array. I can't reference the array either. How should I go about this? Here's the part of code I'm talking about.

void ShuffleDeck(bool &rgCards[]) {
    for (int i = 1; i < 52; ++i) {
        //something
    }
    return rgCards[];
}

All help appreciated.

2012-04-05 21:30
by argoneus


3

You use a std::vector and shuffle the values in it. Preferably, pass it by reference to the function and work on the original vector.

From your snippet, it's not entirely clear what you expect it to do - you pass an array of bool by reference but return it as an int with the syntax rgCards[] which makes absolutely no sense in that context.

EDIT: As per Fred's comment - you can use random_shuffle.

2012-04-05 21:33
by Luchian Grigore
Or just use <code>random_shuffle()</code> on a std::vector instead of rolling your own shuffle function - Fred Larson 2012-04-05 21:35
@FredLarson cool, all the stuff in continues to amaze me. : - Luchian Grigore 2012-04-05 21:37
Yeah well, I didn't really know where I'm going with this but I didn't want not to post any code here. Thanks for the help - argoneus 2012-04-05 21:39


2

From the code snippet you've provided it looks like you're trying to pass a reference to the array to ShuffleDeck(). The C++ syntax for an array reference is data-type (&)[N] where N is the number of elements in the array. Change your function to

void ShuffleDeck( char (&rgCards)[52] ) { ... }

You can make this a template function and have the compiler deduce the array length

template<size_t N>
void ShuffleDeck( char (&rgCards)[N] ) { ... }

Finally, since you're using C++ you should probably switch over to using a container class such as std::array or std::vector instead of a C-style array.

2012-04-05 21:41
by Praetorian


2

You could also do this

void shuffle(int* deck, int size)
{
  for(int i =0; i < size; i++)
  {
    deck[i] = i;
  }
}

This shows that the array is indeed passed as a pointer.

int deck[52];
shuffle(deck,52);
2012-04-05 22:29
by cchampion


1

To keep the code most similar to what you write, I'll just make minimal corrections: note that & isn't required and the index should start from 0.

void ShuffleDeck(bool rgCards[]) {
    for (int i = 0; i < 52; ++i) {
        //something
    }
}

any change you will do to rgCards[i] will be available after the call to ShuffleDeck

2012-04-05 21:53
by CapelliC


0

The cleanest solution, IMO:

class Deck {
  char cards[52];
public:
  void Shuffle();
};

void Deck::Shuffle()
{
  // I can change cards here because both cards and Shuffle are members of Deck
}
2012-04-06 07:13
by MSalters
Ads