Using intptr_t instead of void*?

后端 未结 2 1907
醉话见心
醉话见心 2020-11-28 09:43

Is it a good idea to use intptr_t as a general-purpose storage (to hold pointers and integer values) instead of void*? (As seen here: http://www.cr

2条回答
  •  离开以前
    2020-11-28 10:24

    No, you can't be guaranteed that any particular type is a reasonable way of storing both pointers and integers, and besides, it makes your code confusing. There is a better way.

    If you want to store an integer and a pointer in the same object, the clean and portable method is to use a union:

    union foo {
       int integer_foo;
       void *pointer_foo;
    };
    

    This is portable and allows you to store both sorts of things in the size of storage needed for the larger of the two. It is guaranteed to always work.

提交回复
热议问题