C programming: casting a void pointer to an int?

后端 未结 3 827
谎友^
谎友^ 2021-02-02 11:27

Say I have a void* named ptr. How exactly should I go about using ptr to store an int? Is it enough to write

ptr = (void *)5;

If I want to sav

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 11:52

    That will work on all platforms/environments where sizeof(void*) >= sizeof(int), which is probably most of them, but I think not all of them. You're not supposed to rely on it.

    If you can you should use a union instead:

    union {
        void *ptr;
        int i;
    };
    

    Then you can be sure there's space to fit either type of data and you don't need a cast. (Just don't try to dereference the pointer while its got non-pointer data in it.)

    Alternatively, if the reason you're doing this is that you were using an int to store an address, you should instead use size_t intptr_t so that that's big enough to hold any pointer value on any platform.

提交回复
热议问题