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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With