Reputation: 61
I recently started c++ and I created a class called Deck
that pretty much creates a deck of cards. One of it's functionality is to shuffle a deck. I created a object of type Deck
in main()
and was able to called the shuffle()
member function...which worked! However when I accessed the shuffle()
function using a pointer, Xcode highlights:
Card u1 = *(cards[index]);
and outputs:
Thread 1:EXC_BAD_ACCESS (code = EXE_1386_GPFLT)
Can anyone help me out here?
void Deck::shuffle()
{
srand(static_cast<unsigned int>(time(0)));
for(size_t x = 0;x<cards.capacity();x++)
{
int index = rand()%51;
int index2 = rand()%51;
Card u1= *(cards[index]);
*cards[index] = *cards[index2];
*cards[index2] = u1;
}
}
int main()
{
//Deck p;
//p.shuffle(); //works!
//p.Display();//works!
Deck *p;
p->shuffle(); //does not work!
}
Upvotes: 2
Views: 141
Reputation: 133044
There are several errors in your code.
Deck *p;
p->shuffle(); //does not work!
You've just created a pointer to a deck. Where is the actual deck to which the pointer points to?
You should do
Deck* p = new Deck;
p->Shuffle();
or
Deck theDeck;
Deck* p = &theDeck;
p->Shuffle();
for(size_t x = 0;x<cards.capacity();x++)
You are not allowed to access all elements within the vector's capacity. You should use x < cards.size()
Does your cards
container hold pointers to cards? If it contains actual cards, not pointers to them, then your swap routine should not use dereferenceing (*cards[index]
--> cards[index]
)
Incidentally, if cards
had 52 elements, then you should rand()%52
, not 51.
Upvotes: 2