I have a void * value in a structure and I need to send it through a socket to a server. I know I need to use
int value = htonl(kv->value);
but the compiler is throwing errors
passing argument 1 of ‘htonl’ makes integer from pointer without a cast [-Werror]
I also tried casting the void * to an int, did not work and I used
htonl(*kv->value);
but that also threw errors. How do I get the void * to the right data type?
Side note: The structure is not editable as I am writing a framework.
struct kvpair {
void *value;
};
You can't dereference a void *
type directly, you have to first cast it to something you can dereference and dereference that.
For example
uint32_t value = htonl(*(uint32_t *) kv->value);
This casting and dereferencing requires that kv->value
actually points to something that is the type you try to cast it to. If, in your code, kv->value
points to a single short
value then the above cast and dereferencing will lead to undefined behavior.