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

后端 未结 4 638
忘了有多久
忘了有多久 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:52

    Basically:

    • a T * may be freely converted to a void * and back again (where T * is not a function pointer), and you will get the original pointer.
    • a T * may be freely converted to a U * and back again (where T * and U * are not function pointers), and you will get the original pointer if the alignment requirements are the same. If not, the behaviour is undefined.
    • a function-pointer may be freely converted to any other function-pointer type and back again, and you will get the original pointer.

    Note: T * (for non-function-pointers) always satisfies the alignment requirements for char *.

    Important: None of these rules says anything about what happens if you convert, say, a T * to a U * and then try to dereference it. That's a whole different area of the standard.

提交回复
热议问题