Question

I keep getting an error of:

Unhandled exception at 0x5a6fca58 (msvcr100d.dll) in Gofish.exe: 0xC0000005: Access violation writing location 0x0ff3b113.

The code that I'm trying to run is:

#include <iostream>
#include <string>
#include<Array>
using namespace std;

class Card{
 string suit;
 int rank;
public:
 Card(int a, string b){
  rank=a;
  suit=b;
 }
 Card(){}
 string getSuit(){
  return suit;
 }
 int getRank(){
  return rank;
 }
};

class Deck{
 Card deck [52];
public:
 Deck(){
  for(int i=1; i<=13; i++){
  deck [i]=Card(i, "spades");
  deck [i*2]=Card(i, "hearts");
  deck [i*3]=Card(i, "diamonds");
  deck [i*4]=Card(i, "clubs");
  }
 }
  void list(){
  for(int i=1; i<=52; i++){
   cout << deck [i].getRank() << " of " << deck [i].getSuit() << endl;
   }
  }
};

int main(){
 Deck deck=Deck();
 deck.list();
 system("pause");
 return 0;
}

The compiler I'm using is Microsoft Visual C++ 2010 Express if that might effect anything.

Was it helpful?

Solution

Because arrays are zero based. The highest index in your array is 51 but you are trying to access 52. Also, in your implementation, the first card, at index 0, will never be accessed.

deck [i*4-1]=Card(i, "clubs");

OTHER TIPS

In the array deck of size 52 you are trying to use index 52 which is invalid.

You can change your for loop as:

  for(int i=0; i<52; i+=4){
    deck [i]   = Card(i, "spades");
    deck [i+1] = Card(i, "hearts");
    deck [i+2] = Card(i, "diamonds");
    deck [i+3] = Card(i, "clubs");
  }

This looks like homework so I'll give you some hints:

Check your for loop logic.

Remember that the first entry in an array is 0 not 1.

Besides the array index overflow issue. There might be a problem with this:

int main(){
 Deck deck=Deck();
 // ... 
}

There is no need for that: you could simply write Deck deck; instead. But this way, if your compiler is performing no optimizations, you might end up with code that tries to copy a Deck object using default assingment operator, which performs a memberwise copy. Thus, will try to copy a Card fixed size array, and copying one fixed size array to another will not work properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top