Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of converting from void* to int in c

in my code i have:

int number_compare(void *val1, void *val2) {
    if (*(int*) val1 < *(int*s) val2) {

So basically to convert from void* to int i have to cast *(int *).

This works and give me the correct results, could someone please tell me why though or point me to a thread that explains it. I have already looked and cannot find an answer I understand.

like image 609
cxzp Avatar asked Dec 26 '22 02:12

cxzp


2 Answers

That's not converting a void * to an int. It's interpreting whatever the void * is pointing at as an int. Break it down:

val1           // void pointer - not dereferenceable
(int *)val1    // pointer to 'int'
*(int *)val1   // the 'int' being pointed to

So your function is getting passed two pointers: it then interprets them as pointers to int and dereferences them, comparing the two int values being pointed to.

In contrast, converting from a void * to an int would look something like this:

int x = (int)val1;

But that's almost certainly not what you want - first because int is signed, and pointers aren't, and second because int and pointer types might not be the same size.

like image 151
Carl Norum Avatar answered Jan 04 '23 01:01

Carl Norum


first thing void pointer cannot be defreferenced. maybe because it doesn't yet know how to fetch data. (i.e) if its char should fetch 1 byte, int 4 bytes...

so here first you are converting some address (void pointer) to int pointer.

(int*) val1;

later to fetch the value from that address [now the system knows it should take data from 4 bytes from that address : val1].

*(int*)val1 

this 'll give you the data in that address.

This is formally said to be casting "(data_type) data" casting the data to specified data_type;

like image 23
Dineshkumar Avatar answered Jan 04 '23 01:01

Dineshkumar