开发者

What level of indirection to use in structs?

I want to create a simple structure that holds an identifier of type int and a value of any kind. Should I use

str开发者_开发知识库uct {
    int key;
    void *value;
}

or

struct {
    int key;
    void **value;
}

or something else?


I would use the first since a void* can point to anything. There doesn't appear to be any need for a double indirection in your case.

You should also keep in mind that there is another way, one that involves having a variable size payload within the structure rather than a fixed void*. It's useful in the case where the structures themselves are allocated (such as in a linked list) so you can make them variable sized by adjusting the argument to malloc.

In that case, you can avoid pointers in the structure altogether. See this answer for more details. I'm not suggesting that it's necessary (or even a good idea) for this particular case, just providing it as another possibility. I suspect your option 1 will be more than enough, or supplying a union within the structure if you don't want any pointer in there.


I think You have to use a combination of union and struct:

struct my_struct {
        int key;
        union {
                int a_int;
                float a_float;
                char a_char;
                /* Other types You may need */
        } value;
}

The pointer only points to a variable, it doesn't hold its value. You have to store actual variable somewhere else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜