When is casting void pointer needed in C?

后端 未结 5 1551
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 13:56

I\'ve been looking at Advanced Linux Programming by Mitchell, Oldham and Samuel. I\'ve seen in the section on pthreads something about void pointers and casting tha

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 14:45

    I believe the same code has been referenced in other questions.

    The answer in the second link explains:

    It's not valid. It simply happens to work if sizeof(int) == sizeof(void *), which happens on many systems.

    A void * is only guaranteed to be able to hold pointers to data objects.

    Here is a C FAQ on the subject.

    And the quoted text:

    How are integers converted to and from pointers? Can I temporarily stuff an integer into a pointer, or vice versa?

    Pointer-to-integer and integer-to-pointer conversions are implementation-defined (see question 11.33), and there is no longer any guarantee that pointers can be converted to integers and back, without change

    Forcing pointers into integers, or integers into pointers, has never been good practice

提交回复
热议问题