The only correct way to use this variable to store other data is to copy the data byte by byte:
template <typename T> void store(unsigned char * & p, T const & val) { static_assert(sizeof(unsigned char *) >= sizeof(T)); char const * q = reinterpret_cast<char const *>(&val); std::copy(q, q + sizeof(T), reinterpret_cast<char *>(&p)); }
Using:
unsigned char * p; store(p, 1.5); store(p, 12UL);
Matching search function:
template <typename T> T load(unsigned char * const & p) { static_assert(sizeof(unsigned char *) >= sizeof(T)); T val; char const * q = reinterpret_cast<char const *>(&p); std::copy(q, q + sizeof(T), reinterpret_cast<char *>(&val)); return val; }
Using:
auto f = load<float>(p);
source share