Suppose I have a struct and a file with binary representations of those structs and I’ll make a function/method that access this binary data using ifstream::read().
Here’s an example struct:
struct MyStruct {
int x; //Value interested in
int y; //Value interested in
int anotherInteger; //Not interested
double aDouble; //Not interested
}
How do I make the function (I’ll call it here readData) either: not using pointers when reading or, if using pointers is necessary, where would I put the proper delete?
So far, the relevant part of my readData looks like this:
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
MyStruct *st = new MyStruct[1];
inFile.seekg(sizeof(MyStruct)*pos);
inFile.read((char*) st, sizeof(MyStruct));
returnX = st[0].x;
returnY = st[0].y;
//delete [] st goes here?
}
I’ve tried uncommenting the delete part, but I get an allocation error, probably because the values of x and y are pointing to something that doesn’t exist anymore.
Any ideas on how to solve this?
Why wouldn’t you use a local variable?
Also, references cannot be re-seated. Therefore the assignment assigns the value to the origional
intpassed by the calling function.returnXandreturnYare not pointed at the local variables. In the code above, the assignment changesmainxandmainy.