read address and assign it to pointer

For fun I was making some kind of console 'paint',you could normaly save map and load it, however when my friends tested, they used the "x" to close it, resulting in loss of last picture(i had an inside "exit" function). so i've googled and found the atexit();, but it takes functions without parametres, so i'd have to make a global var to save, that's the easy way, however just for curiosity i've thought of storing the address of the map in an external file. the function at exit should read the address then cast it to a struct pointer(map variable) to save...

so the question is: what type should be the variable with the address and is this the proper way to cast it to struct?
1
2
Mystruct *str;
str=(int*)<the address>;
You are programming in C++ - not C or Java. Use a destructor for deinitialization/cleanup.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <fstream>

template< typename T > struct save_at_exit
{
     explicit save_at_exit( const T& object, const char* path2file )
                : save_this(object), path(path2file) {}

     ~save_at_exit() { std::ofstream file(path) ; file << save_this ; }

     // non-copoyable
     save_at_exit( const save_at_exit& ) = delete ;
     save_at_exit& operator= ( const save_at_exit& ) = delete ;

     const T& save_this ;
     const char* const path ;
};

struct Mystruct
{
    // whatever
    friend std::ostream& operator<< ( std::ostream& stm, const Mystruct& ms ) ;
};

struct Yourstruct
{
    // whatever
    friend std::ostream& operator<< ( std::ostream& stm, const Yourstruct& ys ) ;
};


int main()
{
    
        static Mystruct tobesaved ;
        static const save_at_exit<Mystruct> atexit1( tobesaved, "mystruct.txt" ) ;

        // ...

    

    
        static Yourstruct also2bsaved ;
        static const save_at_exit<Yourstruct> atexit2( also2bsaved, "yourstruct.txt" ) ;

        // ...

    

    // ...
}

Last edited on
I already have a function to save it properly and in a readable format, I'd just need to read the address from a file created, I only need to properly read addres and assign it to the pointer...
> I only need to properly read addres and assign it to the pointer...

The right way to play with fire:

1
2
3
4
5
6
7
8
Mystruct ms ;
outfile << reinterpret_cast<std::size_t>( &ms ) ;

// ...

std::size_t address ;
infile >> address ;
Mystruct* pointer = reinterpret_cast<Mystruct*>(address) ;
Ok thanks! that did the trick! But why is it playing with fire?
> But why is it playing with fire?

a. The code is not guaranteed to work on all implementations - for instance, on one that uses segmented addressing.

b. Any programming error could be a disastrous 'silent' error - the best you can hope for is that an error would cause the program to crash immediately.
Thanks for the explanation!
Topic archived. No new replies allowed.