Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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.

like image 522
Jeff Avatar asked Mar 02 '26 00:03

Jeff


2 Answers

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");
like image 152
Pete Avatar answered Mar 04 '26 15:03

Pete


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");
  }
like image 26
codaddict Avatar answered Mar 04 '26 15:03

codaddict