4 ms·
Ask HN: In C, how to map void* to int propertly
Quick question. If we have `void` how can we translate it to `int`.
For example this:
`static void dfs(SccGraph graph, LinkedStack* stack, bool* visited, void* v)`
I need to mark `v` as visited but how can I quickly convert `void` to `int` so I can mark `visited[(int) v] = true`
I can convert `void` to `int` with a cast but then I need to make sure the size of the `visited` array is prime and not any `n`. Not sure what is the right way to do this.
- krapp 4y agostupid question - why aren't you just passing an int (or size_t) to begin with, or a struct pointer instead of a void pointer?
- jjgreen 4y agovisited[*((int*)v)] = true
- amir734jj 4y ago`v` is just a pointer a struct.
- arthurcolle 4y agoyeah this dude has the right idea lol, we answered the same thing but you were much more to the point
- deleted 4y ago[deleted]
- Nokinside 4y agovoid* void_pointer = v; int* pointer_to_a_int = (int*) v; int int_v_points_to = *(int*)v;
- samsaga2 4y agoInts are 32 bits and pointers are 64 bits (https://www.ibm.com/docs/en/ibm-mq/9.1?topic=platforms-standard-data-types-unix-linux-windows https://www.ibm.com/docs/en/ibm-mq/9.1?topic=platforms-stand...). Converting from pointer to int you are truncating the value from 64 bits to 32 (discarding the high 32 bits). You are losing information, so, two different nodes with different pointers addresses could have the same int. Also, a bool array to store all the visited nodes will be really huge (memory address can have very high numbers). A better solution is to use a hash table (for ex. std::unordered_map<void*, bool>).