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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 tomalloc.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.