I am trying to create a simple card shuffling and dealing simulator. I am using a vector to represent a deck of 52 cards and each card is represented by the structure BitCard
whose elements' space is memory is limited by bitfields. But when the constructor tries to access the vector, xCode throws a BAD_ACCESS exception: Thread 1: EXC_BAD_ACCESS (code =1 address = 0x0)
. I've done some research and found that this exception is linked with a null pointer but can't seem to figure out how to fix it. My code is as follows:
#include <iostream>
#include <cctype>
#include <cstdlib>
#include <vector>
#include <iomanip>
using namespace std;
struct BitCard{
unsigned face:4;
unsigned color:1;
unsigned suit:2;
};
class DeckOfCards {
public:
static const int faces = 13;
static const int colors = 2;
static const int numberOfCards = 52;
DeckOfCards();
void shuffle();
void deal();
private:
vector <BitCard> deck={};
};
DeckOfCards::DeckOfCards(){
for (int i = 0; i <numberOfCards;++i){
deck[i].face = i%faces;
deck[i].suit = i/faces;
deck[i].color = i/(faces*colors);
}
}
void DeckOfCards:: shuffle(){
for (int i = 0; i <numberOfCards;i++){
int j = rand()%numberOfCards;
BitCard tmp = deck[i];
deck[i] = deck[j];
deck[j] = tmp;
}
}
void DeckOfCards:: deal(){
for (int k1 = 0, k2 = k1+numberOfCards/2;k1<numberOfCards/2-1;k1++,k2++)
{
cout << "Color:" << setw(3) << deck[k1].color
<< " Card:" << setw(3) << deck[k1].face
<< " Suit:" << setw(3) << deck[k1].suit
<< " Color:" << setw(3) << deck[k2].color
<< " Card:" << setw(3) << deck[k2].face
<< " Card:" << setw(3) << deck[k2].suit;
}
}
int main(int argc, const char * argv[]) {
DeckOfCards testDeck;
testDeck.shuffle();
testDeck.deal();
return 0;
}
The exception is generated in line
deck[i].face = i%faces;
How can I fix this? Thanks in advance!