When is casting between pointer types not undefined behavior in C?

后端 未结 4 641
忘了有多久
忘了有多久 2020-11-27 12:55

As a newcomer to C, I\'m confused about when casting a pointer is actually OK.

As I understand, you can pretty much cast any pointer type to any other type, and the

4条回答
  •  天涯浪人
    2020-11-27 13:55

    Generally, if as usual nowadays the pointers themselves have the same alignment properties, the problem is not the cast itself, but whether or not you may access the data through the pointer.

    Casting any type T* to void* and back is guaranteed for any object type T: this is guaranteed to give you exactly the same pointer back. void* is the catch all object pointer type.

    For other casts between object types there is no guarantee, accessing an object through such a pointer may cause all sorts of problems, such as alignments (bus error), trap representations of integers. Different pointer types are not even guaranteed to have the same width, so theoretically you might even loose information.

    One cast that should always work, though, is to (unsigned char*). Through such a pointer you may then investigate the individual bytes of your object.

提交回复
热议问题