473,808 Members | 2,855 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with nested class or array overrun.

I'm trying to make a class that represents a deck of cards and a
dealer for use in a card game. I'm fairly novice. The code compiles
(Dev c++(gcc 3.3.1)) without complaint, however it acts strange when I
run it. (In windows), when I double-click or run the prog from the
IDE, it displays the deck, then exits. When I run it from a console
window, if I type the filename eg "cards.exe" , it displays the cards
as expected but doesn't pause at the end of the program. However if
I type "cards" without the explicit exe extension, the cards are not
displayed and I get the message:
"This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information."

Any help is greatly appreciated. Joe
_______________ _______________ ___________
#include <iostream>
#include <stdint.h>
#include <string>

using namespace std;

struct acard{
int suit;
int value;
uint32_t index; // to be used by shuffle function
};

class deck{
private:
string theSuits; // contains suits in order
string theValues; // contains values in order
acard* card; // an array of cards
int numcards;

public:
deck();
~deck();
void show();
// void shuffle();
};

deck::deck():
theSuits("\x05\ x04\x03\x06") //c, d, h, s
,theValues("234 56789TJKQA")
,numcards(theSu its.length() * theValues.lengt h())
,card(new acard[numcards])

{
int cardnum(0);
for(int i = 0; i < theSuits.length (); ++i){
for(int j = 0; j < (theValues.leng th()); ++j){
cardnum = ((i * theValues.lengt h()) + j);
card[cardnum].suit = i;
card[cardnum].value = j;
}
}
}

deck::~deck(){
delete [] card;
}

void deck::show(){
for (int i=0; i < numcards; ++i){
cout << theValues[card[i].value]
<< theSuits[card[i].suit] << endl;
}
}
int main()
{
deck mydeck;
mydeck.show();

system("pause") ;
return 0;
}
_______________ _______________ ______
Jul 22 '05 #1
7 1918
J. Campbell wrote:
I'm trying to make a class that represents a deck of cards and a
dealer for use in a card game. I'm fairly novice. The code compiles
(Dev c++(gcc 3.3.1)) without complaint, however it acts strange when I
run it. (In windows), when I double-click or run the prog from the
IDE, it displays the deck, then exits. When I run it from a console
window, if I type the filename eg "cards.exe" , it displays the cards
as expected but doesn't pause at the end of the program. However if
I type "cards" without the explicit exe extension, the cards are not
displayed and I get the message:
"This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information."

Any help is greatly appreciated. Joe
Regarding the message you get from your OS, I think you should ask in the
newsgroup for that OS. Regarding the code, see below.
_______________ _______________ ___________
#include <iostream>
#include <stdint.h>
No such standard header. Yet.
#include <string>

using namespace std;

struct acard{
int suit;
int value;
uint32_t index; // to be used by shuffle function
No such standard type. Yet. Use at your own risk.
};

class deck{
private:
string theSuits; // contains suits in order
string theValues; // contains values in order
acard* card; // an array of cards
int numcards;
Swap the two lines before above. The explanation is in my next
paragraph.

public:
deck();
~deck();
void show();
// void shuffle();
};

deck::deck():
theSuits("\x05\ x04\x03\x06") //c, d, h, s
,theValues("234 56789TJKQA")
,numcards(theSu its.length() * theValues.lengt h())
,card(new acard[numcards])
This is very wrong. The initialisation happens in the order of the
declarations, not in the order you wrote in the initialiser list. So,
when you initialise the "card" member, "numcards" still contains trash.
What you allocate is impossible to say. Move the declaration of the
'numcards' member _before_ the 'card' member.

{
int cardnum(0);
for(int i = 0; i < theSuits.length (); ++i){
for(int j = 0; j < (theValues.leng th()); ++j){
cardnum = ((i * theValues.lengt h()) + j);
You might want to reconsider the use of superfluous parentheses. It
makes the code harder to read.
card[cardnum].suit = i;
card[cardnum].value = j;
}
}
}

deck::~deck(){
delete [] card;
}

void deck::show(){
for (int i=0; i < numcards; ++i){
cout << theValues[card[i].value]
<< theSuits[card[i].suit] << endl;
}
}
int main()
{
deck mydeck;
mydeck.show();

system("pause") ;
The behaviour of 'system' is implementation-defined. There is no way
to predict what it will do. If you simply need to pause your program,
you might want to use getchar().
return 0;
}

Victor
Jul 22 '05 #2

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:Ty******** *******@newsrea d1.dllstx09.us. to.verio.net...
class deck{
private:
string theSuits; // contains suits in order
string theValues; // contains values in order
acard* card; // an array of cards
int numcards;


Swap the two lines before above. The explanation is in my next
paragraph.

public:
deck();
~deck();
void show();
// void shuffle();
};

deck::deck():
theSuits("\x05\ x04\x03\x06") //c, d, h, s
,theValues("234 56789TJKQA")
,numcards(theSu its.length() * theValues.lengt h())
,card(new acard[numcards])


This is very wrong. The initialisation happens in the order of the
declarations, not in the order you wrote in the initialiser list. So,
when you initialise the "card" member, "numcards" still contains trash.
What you allocate is impossible to say. Move the declaration of the
'numcards' member _before_ the 'card' member.

Victor


Thanks Victor. What a critical mistake! I confess ignorance. I thought,
as you guessed, that the order was as-per the initialiser list...

I included the compiler info to cover bases, since I couldn't figure it out
what was going wrong...and the OS-specific call, because...well. ..I won't
try to justify it...

Thanks again for the real help...this detail will carry forward. I wish I
could pay you back. Your helping karma is golden.

Joe
Jul 22 '05 #3
One detail I forgot to ask. Suppose I have a class where the initialization
order is critical, and that the order alternates between public and private.
Does it become necessarry to do something like this?:

class myclass{
public:
int ImFirst;
private:
int ImSecond;
public:
int ImThird;
private:
int ImFourth;
};

Thanks again.
Jul 22 '05 #4
Joe C wrote:
One detail I forgot to ask. Suppose I have a class where the initialization
order is critical, and that the order alternates between public and private.
Does it become necessarry to do something like this?:

class myclass{
public:
int ImFirst;
private:
int ImSecond;
public:
int ImThird;
private:
int ImFourth;
};


I've never seen anything like this, but I suppose if the requirement is so
unusual, so should be the syntax.

Let me just note here that if the order of initialisation is important to
the point when you have to introduce some weirdness to the class, you may
need to rethink your design, reconsider the reasons according to which the
order of initialisation has to be specific. And also, if you ever need
the data members to be public, you should also think twice. I cannot
remember ever having to have both private and public data in the same
class. The data are either all public or all private (and much more often
the latter than the former).

Victor
Jul 22 '05 #5
ma**********@ya hoo.com (J. Campbell) wrote:
I'm trying to make a class that represents a deck of cards and a
dealer for use in a card game. I'm fairly novice.
First lesson... don't manually manage memory when there's an easier way.
#include <iostream>
#include <stdint.h>
#include <string>
#include <vector>

using namespace std;

struct acard{
int suit;
int value;
uint32_t index; // to be used by shuffle function
};

class deck{
private:
string theSuits; // contains suits in order
string theValues; // contains values in order
Are the suits and values ever going to change during a game? If not,
then use:
string const theSuits;
etc.

Are they specific to this deck? If all decks will have the same suit
and values then you should either make these items static, or remove
them from the class entirely. Also it is considered good design
these days to have code that populates the deck, not actually as a
member function of the deck, ie. when you create a new deck, it
starts off blank and the constructor does as little as possible;
and then you have a free function that takes a deck as reference
parameter and adds all the cards to it.
acard* card; // an array of cards
int numcards;
Replace these two with:
vector<acard> card;
public:
deck();
~deck();
void show();
// void shuffle();
Use std::random_shu ffle() instead of writing your own shuffle. Again
it would be good design for this to not be a member function.
};

deck::deck():
theSuits("\x05\ x04\x03\x06") //c, d, h, s
,theValues("234 56789TJKQA") ,numcards(theSu its.length() * theValues.lengt h())
,card(new acard[numcards])
,acard(theSuits .length() * theValues.lengt h())
deck::~deck(){
delete [] card;
}


You don't need this function at all now. The rest of the program
stays the same

If you stuck with your pointer approach, then you would also have to
add a copy-constructor and an assignment operator.
Jul 22 '05 #6
Old Wolf wrote:
ma**********@ya hoo.com (J. Campbell) wrote:

I'm trying to make a class that represents a deck of cards and a
dealer for use in a card game. I'm fairly novice.

First lesson... don't manually manage memory when there's an easier way.

#include <iostream>
#include <stdint.h>
#include <string>

#include <vector>
using namespace std;

struct acard{
int suit;
int value;
uint32_t index; // to be used by shuffle function
};

class deck{
private:
string theSuits; // contains suits in order
string theValues; // contains values in order

Are the suits and values ever going to change during a game? If not,
then use:
string const theSuits;
etc.

Are they specific to this deck? If all decks will have the same suit
and values then you should either make these items static, or remove
them from the class entirely. Also it is considered good design
these days to have code that populates the deck, not actually as a
member function of the deck, ie. when you create a new deck, it
starts off blank and the constructor does as little as possible;
and then you have a free function that takes a deck as reference
parameter and adds all the cards to it.

acard* card; // an array of cards
int numcards;

Replace these two with:
vector<acard> card;

public:
deck();
~deck();
void show();
// void shuffle();

Use std::random_shu ffle() instead of writing your own shuffle. Again
it would be good design for this to not be a member function.

};

deck::deck( ):
theSuits("\x05\ x04\x03\x06") //c, d, h, s
,theValues("234 56789TJKQA")


,numcards(theSu its.length() * theValues.lengt h())
This is not needed if 'numcards' is not there any more, right?
,card(new acard[numcards])

,acard(theSuits .length() * theValues.lengt h())


Actually

, card(theSuits.l ength() * theValues.lengt h())

deck::~deck() {
delete [] card;
}

You don't need this function at all now. The rest of the program
stays the same

If you stuck with your pointer approach, then you would also have to
add a copy-constructor and an assignment operator.


How true...

V
Jul 22 '05 #7
Victor Bazarov <v.********@com Acast.net> wrote:
Old Wolf wrote:
ma**********@ya hoo.com (J. Campbell) wrote:
,card(new acard[numcards])

,acard(theSuits .length() * theValues.lengt h())


Actually
, card(theSuits.l ength() * theValues.lengt h())


Right. All the more reason to use a better naming convention than
"acard" as a typename and "card" as an acard.
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2625
by: J. Campbell | last post by:
I have a class that I want to contain a const data-member equivalent to eg: int array = {7,11,13,17,19,23,29,31}; What's the simplest way to create such a table inside a class? Thanks, Joe
5
3340
by: Carmine Cairo | last post by:
Hi, I'm working on a project and today I've note a little problem during the compile fase. Here a little piece of code: // 1st version welldone = 0; size = p->getSize(); backbone = new rightType;
1
2369
by: elixxir | last post by:
Hiho, I'm trying to deserialize the following XML feed from the weather channel but I'm having an issue with the nested arrays. I got as far as getting the 'day' into arrays but I can't get the 'part' nested array working. This is my first hack at XML feeds and such, so any pointers as to how to best do this or references/tutorials would be good. (I'm doing all this in .NET 2.0 btw)
6
559
by: B0nj | last post by:
I've got a class in which I want to implement a property that operates like an indexer, for the various colors associated with the class. For instance, I want to be able to do 'set' operations like MyClass.MyColors = Color.Green or, a 'get', such as Color forecolor = MyClass.MyColors; I want to use an indexer so I can take parameters, such as the color type (e.g. "Foreground", "Background" etc.). With a single member function I couldn't...
7
2427
by: Ryan Shaw | last post by:
I’m having a small problem with inheritance with a hierarchy of classes The example is Class Class Private m_classB as Class Class Class End Clas End Clas
26
3411
by: Adam Warner | last post by:
Hi all, One cannot return a pointer to an array type in C because C has no first class array types. But one can return a pointer to a struct containing an incomplete array via the illegal but widely supported zero array struct hack: #include <stdlib.h> typedef struct byte_vector_t byte_vector_t;
3
6353
by: raylopez99 | last post by:
Below is my problem. I've narrowed it down to one thing: my unfamiliarity on how class instances are instantiated in an array. This is because the "un-array" / "non-array" version of the program works fine (see below). So what is the problem? I get a null reference on the line below at *!&!* "Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.? RL
1
5332
by: =?Utf-8?B?QmFybmV5TGlnaHQ=?= | last post by:
Hi, I have a WCF service contract which has message containing a List<MyType> data member where MyType consists of a string Key and object Value. As expected this gets exposed as a MyType array in the service reference. In the client, I dynamically add Key/Value entries in the list. This works fine as long as I use simple types in the client, but I need to
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10628
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10373
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5547
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5685
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3859
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.