C++: Is it safe to cast pointer to int and later back to pointer again?

前端 未结 12 1794
梦如初夏
梦如初夏 2020-11-28 11:38

Is it safe to cast pointer to int and later back to pointer again?

How about if we know if the pointer is 32 bit long and int is 32 bit long?

long* j         


        
12条回答
  •  [愿得一人]
    2020-11-28 12:41

    To an int ? not always if you are on a 64 bit machine then int is only 4 bytes, however pointers are 8 bytes long and thus you would end up with a different pointer when you cast it back from int.

    There are however ways to get around this. You can simply use an 8 byte long data type ,which would work whether or not you are on 32/64 bit system, such as unsigned long long unsigned because you don't want sign extension on 32-bit systems.

    It is important to note that on Linux unsigned long will always be pointer size* so if you are targeting Linux systems you could just use that.

    *According to cppreference and also tested it myself but not on all Linux and Linux like systems

提交回复
热议问题