I’m trying to create a struct that can hold generic values. The code below works but I’m getting a compiler warning about the cast from pointer to integer. This is on a 64-bit system.
struct node
{
void *key;
void *value;
};
void insert(struct node *ht, void *key, void *value)
{
ht->key = key;
ht->value = value;
return;
}
int main()
{
struct node *t = (struct node *)malloc(sizeof(struct node));
insert(t, (void *)3, (void *)5);
printf("[%d]->[%d]\n", (int)t->key,(int)t->value);
free(t);
return 0;
}
I’m not even sure if this is the correct way to go about it. I sort of hacked it up. Please let me know if there is a proper way to do this.
The compiler tries to warn you that you lose bits when casting from
void *toint. It doesn’t know that thevoid *is actually anintcast, so the lost bits are meaningless.A double cast would solve this
(int)(uintptr_t)t->key.It first casts
void *touintptr_t(same size, no warning), thenuintptr_ttoint(number to number, no warning).You need to include
<stdint.h>to have theuintptr_ttype (an integral type with the same size as a pointer).