Search code examples
c++pointerscastingunsigned-integer

Storing unsigned integer in a pointer


I'm constructing an octree data structure, and to save memory for the final nodes I would like the store the values directly in the pointer instead of having to create an object that's made to hold 8 children.

My data type is a uint32_t which means that a pointer have enough bits to hold it on either x86 or amd64.

So how do I store an unsigned 32bit integer in a x86 or amd64 pointer?

pseudo code:

uint32_t i = 123;
Octree* ptr = i;
uint32_t ii = ptr;
std::cout << ii << std::endl; //Prints 123

How is this possible?


Solution

  • Storing an unsigned integer straight in a pointer portably isn't allowed, but you can:

    • do the reverse: you can store your pointer in an unsigned integer; specifically, uintptr_t is explicitly guaranteed by the standard to be big enough to let pointers survive the roundtrip;
    • use a union:

      union NodePtr {
          Octree *child;
          uint32_t value;
      }
      

      here child and value share the same memory location, and you are allowed to read only from the one where you last wrote; when you are in a terminal node you use value, otherwise use child.