I'm having trouble reading and writing a dynamically allocated array of structs to a file. I think it has to do with the way I'm allocating memory, because if I statically allocate them (i.e. vector vectout[3]) then it seems to work better, but I still get a debug assertion error with something about an invalid heap.
With the code the way it is displayed below, the file it outputs has random numbers in it, and I get a debug assertion error about an invalid block type.
Note: this is just some test code...in the real code, I'm reading the number of vectors from a header, dynamically allocating an array, and then reading them all into the array.
Any help is appreciated. Thanks.Code:#include <iostream> #include <fstream> using namespace std; struct vector { float x, y, z; }; int main(int argc, char* argv[]) { vector *vectout; vector *vectin; vectout = new vector[3]; vectin = new vector[3]; vectout[0].x = 1.0f; vectout[0].y = 11.0f; vectout[0].z = 111.0f; vectout[1].x = 2.0f; vectout[1].y = 22.0f; vectout[1].z = 222.0f; vectout[2].x = 3.0f; vectout[2].y = 33.0f; vectout[2].z = 333.0f; for (int i = 0; i < 3; i++) { cout << "vectout[" << i << "] x: " << vectout[i].x << " y: " << vectout[i].y << " z: " << vectout[i].z << endl; } ofstream out; out.open("vector.dat", ios::out | ios::binary); out.write((char *) &vectout, sizeof(vector) * 3); out.close(); ifstream in; in.open("vector.dat", ios::in | ios::binary); in.read((char *) &vectin, sizeof(vector) * 3); in.close(); for (int i = 0; i < 3; i++) { cout << "vectin[" << i << "] x: " << vectin[i].x << " y: " << vectin[i].y << " z: " << vectin[i].z << endl; } delete [] vectin; delete [] vectout; return 0; }



LinkBack URL
About LinkBacks


