et me start by saying I know this is a funky way to program, but my teacher is requiring us to go about it this way.
also:
I CANT use std::string, classes, constructors for this project.
I am required to use this archaic method of c-style strings with dynamic memory allocation occuring outside the struct.. i know its not the best way to go about this, but theres nothign i can go. :(
I have a struct
struct card
{
char *suit;
char *rank;
int cvalue;
}
I've created a pointer of size 52 for my deck
card *deckPtr = new card[52];
card *deckHome = &deckPtr[0];
I then try to use
for(int i=0;i<52;i++)
{
(*deckPtr).suit = new char[8];
(*deckPtr).rank = new char[7];
deckPtr++
}
deckPtr=deckHome;
I am essentially trying to fill in these arrays from a card file, but I cannot make it past running the program, i get sa seg fault which I dont understand why.
I dynamically allocate memory in my card read in function..
void cardInit(card *deckPtr)
{
card *deckHome = &deckPointer[0];
ifstream fin;
char *finName = new char[13];
cin >> *finName
fin.open(finName)
.
.
.
while(fin.good())
{
for(deckPointer=&deckHome[0];deckPointer<&deckHome[52];deckPointer++)
{
fin >> (*deckPointer).suit;
fin >> (*deckPointer).rank;
fin >> (*deckPointer).cvalue;
}
}
Its a pretty simple program..and my dynamic memory works for the file name, but I cant figure out why it doesnt work for structs?
This loop is sketchy. Do you really want to rewrite whole array several times?
Also: &deckPtr[0] is equal to deckPtr &deckHome[52] is equal to deckHome + 52 (*deckPointer).suit; use deckPointer->suit;
Mind posting whole code here? Or at least minimal compiling version stripped of anything not related and which does have this problem? And make use of code tags, they looks like <> on the right panel.
Also:
I CANT use std::string, classes, constructors
You are actually do use them: C++ does not have C structs and only have struct keyword with specific default access modifiers as a backward compatibility. Even if you do not provide a constructor, compiler would generate one for you.