When is an integer<->pointer cast actually correct?

后端 未结 15 2673
北荒
北荒 2020-12-13 07:48

The common folklore says that:

  • The type system exists for a reason. Integers and pointers are distinct types, casting between them is a malpractice in the m

15条回答
  •  没有蜡笔的小新
    2020-12-13 08:36

    I've used such systems when I'm trying to walk byte-by-byte through an array. Often times, the pointer will walk multiple bytes at a time, which causes problems that are very difficult to diagnose.

    For example, int pointers:

    int* my_pointer;
    

    moving my_pointer++ will result in advancing 4 bytes (in a standard 32-bit system). However, moving ((int)my_pointer)++ will advance it one byte.

    It's really the only way to accomplish it, other than casting your pointer to a (char*). ((char*)my_pointer)++

    Admittedly, the (char*) is my usual method since it makes more sense.

提交回复
热议问题