0

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;
};
  • 3
    What does the `void*` actually represent in your code? What exactly are you pointing at that needs to be sent over the network? `htonl()` and `ntohl()` only works on integers, not on pointers. *IF* the `void*` contains the actual integer value itself, rather than pointing at an integer elsewhere in memory, then you can type-cast the `void*` as-is, eg: `uint32_t value = htonl((uint32_t)(kv->value));` *IF* the `void*` points at an integer elsewhere in memory, you need to type-cast the pointer and then dereference it to get the pointed value, eg: `uint32_t value = htonl(*(uint32_t*)(kv->value));` – Remy Lebeau Apr 27 '16 at 17:14
  • 2
    A pointer value in one process has no meaning to another process. What kind of data are you actually trying to pass around? – dbush Apr 27 '16 at 17:14

1 Answers1

3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • This assumes the `void*` is pointing at a `long` variable stored elsewhere in memory. – Remy Lebeau Apr 27 '16 at 17:15
  • @RemyLebeau Just added a note about that. – Some programmer dude Apr 27 '16 at 17:16
  • 1
    If the `void*` points at a `short` variable, then you need to cast the `void*` to a `short*` instead of a `uint32*`. You have to cast to the correct data type. But it is perfectly fine to pass a `short` value to `htonl()`, it will simply be extended to 32 bits. Otherwise, use `htons()` instead. – Remy Lebeau Apr 27 '16 at 17:19