Hacker News new | past | comments | ask | show | jobs | submit login
Ask HN: In C, how to map void* to int propertly
3 points by amir734jj on Oct 16, 2022 | hide | past | favorite | 6 comments
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.




Ints are 32 bits and pointers are 64 bits (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>).


stupid question - why aren't you just passing an int (or size_t) to begin with, or a struct pointer instead of a void pointer?


    void* void_pointer = v;  
    int*  pointer_to_a_int = (int*) v;  
    int   int_v_points_to = *(int*)v;


    visited[*((int*)v)] = true


yeah this dude has the right idea lol, we answered the same thing but you were much more to the point


`v` is just a pointer a struct.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: