I need to compare the values of two void pointers in C. In the code below, I'm getting the console print out that they are different. It seems that the comparison is between the addresses contained in these two void pointers.
How can I make it so that the code compares values (ie: 1 == 1) of the void pointers and prints "same"?
int main(void)
{
int i = 1;
int j = 1;
void *pi = &i;
void *pj = &j;
if (pi == pj) {
printf("same.\n");
} else {
printf("different.\n");
}
return 0;
}
You have to know what type of data the void pointers really point at, coerce the pointers to point to that type, and then dereference the coerced pointers (and assume that the types are comparable using ==):
if (*(int *)pi == *(int *)pj)
printf("same.\n");
else
printf("different.\n");
It's a lot easier just to compare the original variables:
if (i == j)
…
or to use correctly typed pointers:
int *pi = &i;
int *pj = &j;
if (*pi == *pj)
…
What happens in the case that I do not know the type of data (assuming that an user will always pass the same type of data to be compared with my linked list delete method)?
Then life gets difficult. Ideally you get the programmer to pass you a comparator function — see bsearch() and
qsort() from the Standard C library for examples.
Failing that, you need to know the size of the target type and you hope that memcmp() will do the job sufficiently well. That's far from guaranteed — it is not clear that comparing two double values with memcmp() will always produce the correct answer (it might claim different representations of NaN are different, for example), and comparing struct types with padding is fraught, and it wouldn't work correctly for your linked list data type if you're passed the nodes (it might be OK if you're passed the data fields from the two nodes).
If you needed to do ordering rather than just equality (a binary search tree, for example), then the situation is worse — in that case, require the programmer to supply the comparator function.
The pointers are different. If you are trying to compare the integers the pointers point to, then you want
if ( *(int*)pi == *(int*)pj ) {
//some code...
}
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