vitek wrote:there are so many things wrong with that code I don't even know where to start.
Ditto,
Code: Select all
d = reinterpret_cast<Data*>(&chr);
Here you are casting a char** (Note the double pointer!) that eventually leads to another double pointer (Data**), that eventually leads to an uninitialized Data pointer! In all honesty, simply keeping track of all the absurdities is giving me a headache...
How about we start from scratch?
Code: Select all
struct Data
{
int i;
int y;
Data() : i(0), y(0){} // Use a member initialization list here, it's a little faster. (Although for primitive data types like integers that's a moot point.)
};
// Put the class in a char buffer.
char* buffer = new char[sizeof(Data)];
Data* data = new Data();
memcpy(buffer, data, sizeof(Data));
// Read it back.
Data* anotherData = new Data();
memcpy(anotherData, buffer, sizeof(Data));
printf("I = %d\n",anotherData->i);
// DELETE EVERYTHING!!!
delete data;
delete anotherData;
delete [] buffer; // Make sure to use [] here!, since it is an array.
Cheers, this should do the trick...
EDIT: Posted at the same time as Vitek!, I fully agree with what he's saying, simply putting them in a string isn't doing anything useful, since you have to copy the memory to the file/binary socket whatever eventually anyway, it's better to do it in one go. Eg. fwrite(data, sizeof(Data), 1, file);
For converting between endianness check out htonl() and ntohl() (Host to net long and net to host long.).