问题
In the below:
int cmp (void* x, void*y) {
printf("x: %s | y: %s\n", (char*) x, (char*) y);
return 0;
}
int main(int argc, char *argv[]) {
char * strings[] = {"xml", "json"};
qsort(strings, sizeof(strings), sizeof(strings[0]), cmp);
}
How would one see what the values of x
,y
are? The current approach produces gibberish such as:
x: 2?|?? | y: 2?|??
回答1:
Read the documentation of qsort
again. The arguments passed to your comparison function are not the objects to be compared, they are pointers to those objects. So x,y
are not the strings themselves (i.e. the pointers to the characters of the strings), but pointers to those pointers.
Thus you want to write
int cmp (void *x, void *y) {
printf("x: %s | y: %s\n", *(char**) x, *(char**) y);
return 0;
}
Also see Joshua's answer about the problem with the size arguments to qsort
.
Finally, the qsort
comparison function is supposed to take pointers to const void
, not just void
. And it is good practice to keep things const
when you do not intend to modify them. In this case, you do not intend to modify the pointer that x
points to, nor the characters that *x
points to. So it would be even better to write
int cmp (const void *x, const void *y) {
printf("x: %s | y: %s\n", *(const char* const *) x, *(const char* const *) y);
return 0;
}
回答2:
sizeof(strings)
does not return the number of elements in strings
but rather something larger. Your program is undefiend. You want sizeof(strings)/sizeof(strings[0])
.
While passing sizeof(argv[0])
for the third argument happens to work, you really should say sizeof(strings[0])
otherwise your code is hard to read.
The gibberish is caused by qsort
reading out of range on array strings
and passing wild pointers to cmp
. Most of the nonsense is unprintable so you get lots of ? characters.
Nate Eldredge caught the other half. a
and b
arguments to cmp
should be cast to char **
not char *
.
来源:https://stackoverflow.com/questions/58045052/printing-values-of-type-void