0

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

struct {
    int key;
    void *value;
}

or

struct {
    int key;
    void **value;
}

or something else?

matthias krull
  • 4,389
  • 3
  • 34
  • 54
ryyst
  • 9,563
  • 18
  • 70
  • 97

2 Answers2

4

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.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • So far, I always stored a pointer as my value. Since all pointers are equal in size on a given system (true?), I don't really have to keep track of the size. – ryyst Mar 20 '11 at 15:47
0

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.

Michas
  • 8,534
  • 6
  • 38
  • 62