Search code examples
c++structbinaryfiles

Save struct with an array of pointers into a file


I'm working on c++ and I need to save this struct into a file:

struct myStruct{
    int value;
    int value2;
    MyClass * myClass[10];
};

The way that I'm saving this struct is the following:

myStruct my_struct;

my_struct.value = 1;
my_struct.value2 = 2;
for ( int i = 0; i < 10; i++){
    my_struct.myClass[i] = new MyClass();
} 

FILE* f = fopen(path.c_str(), "wb");

if ( f != NULL){

    fwrite(&my_struct, sizeof(myStruct), 1, f);
    fclose(f);
}

But, when I want to read this file, my program crashes when try to access to the array of "MyClass":

FILE* f = fopen(path.c_str(), "rb");

        if ( f != NULL){

            fread(&my_struct2, sizeof(struct myStruct), 1, f);
            fclose(f);
        }


        for ( int i = 0; i < 10; i ++ ){

            if ( my_struct2.myClass[i] != NULL ){

                //Here is the crash
            }
        }

I've been searching but I can't find a solution. I only find topics about arrays of structs. I know that maybe I'm not searching very well.

Thanks.


Solution

  • Your MyStruct contains twenty pointers to other structures.

    By fwrite()ing the contents of your MyStruct to a file, you have successfully written twenty raw memory addresses of your other structures into the file, together with the other members of the MyStruct class.

    Which, of course, is utterly meaningless when you try to read them back in another process. You've read back twenty raw memory addresses. Which mean nothing to a completely unrelated process. And, accessing those memory addresses, unsurprisingly, leads to a crash since those memory addresses, for all intents and purposes, are completely random values.

    What your code needs to do is not write twenty raw pointer addresses to the file, but the contents of those pointers, and what they point to.