This is exactly the same question title as found here - I would also like to store a memory address in a variable - or rather, a void*
in a variable. However, I'd rather store it in some form of an int
rather than a string
, as I'd like to cast it back to a pointer afterwards.
This is because it is a member of a class that I would then like to serialize with boost serialize, and if I did use a void*
, boost serialize might try to store what the pointer is pointing to, which wouldn't be very sensible in my case.
I need this for 32 and 64 bit gcc and MSVC, so basically I was wondering whether there was an inbuilt integer type that was the size of pointers on the same platform. Alternatively, I guess I would need to IFDEF
my own type?
The main memory (or simply the memory) is where variables and other information are stored while a program runs. From the perspective of a program, the computer's memory is a collection of bytes, each with an integer address.
You can do it, but it's not portable. On an x86-64 architecture, for example, a pointer occupies 64 bits, but an int is only 32 bits wide. If you try to store a pointer in an int, truncation will occur.
Storing the value of the pointer (i.e. the memory location of some variable) in a string can be done much like you've used printf: char buf[128]; void *s = malloc (size); sprintf(buf, "%p\n",s);
An address is a non-negative integer. Each time a program is run the variables may or may not be located in same memory locations.
intptr_t
and uintptr_t
are integer types that are large enough to hold a void*
. They are defined by C++11 in <cstdint>
and by C99 in <stdint.h>
If uintptr_t
is not available, you could try uintmax_t
, defined in the same header(s) or by Boost in <boost/cstdint.hpp>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With