Jeff
Jeff

Reputation: 153

"Access violation" error when running C++ program

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.

Upvotes: 2

Views: 3591

Answers (4)

Antonio P&#233;rez
Antonio P&#233;rez

Reputation: 6962

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.

Upvotes: 0

codaddict
codaddict

Reputation: 454950

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");
  }

Upvotes: 3

Pete
Pete

Reputation: 10871

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");

Upvotes: 6

kkress
kkress

Reputation: 807

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.

Upvotes: 0

Related Questions