问题描述
我一直在 Kernighan 和 Pike 合着的一本名为编程实践"的书中学习 C 编程.根据本书中的材料,我编写了一个小程序,用于对命令行上给出的整数数组进行排序.
I have been studying C programming from a book called "The Practice of Programming" by Kernighan and Pike. Based on the material in this book I have written a small program to sort an array of integers given on the command line.
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 30
char *progname;
int arr[MAXSIZE];
int icmp(int *, int *);
int main(int argc, char *argv[]) {
int i;
progname = argv[0];
if (argc == 1) {
fprintf(stderr, "usage: %s [int ...]\n", progname);
exit(1);
}
for (i = 0; argc > 1 && i < MAXSIZE; i++, argc--) {
arr[i] = atoi(argv[i+1]);
}
int n = i;
qsort(arr, n, sizeof(*arr), icmp);
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
exit(0);
}
int icmp(int *p1, int *p2) {
int v1 = *p1;
int v2 = *p2;
if (v1 < v2) {
return -1;
} else if (v1 == v2) {
return 0;
} else {
return 1;
}
}
是的,我的小程序似乎可以运行,我对此很满意.然而,我的实现与书中给出的不同,它似乎没有正确地对整数进行排序.作者将 icmp() 定义为:
Yes, my little program seems to work and I am quite happy with it. However, my implementation differs from the one given in the book, which does not seem to sort integers correctly. The authors define icmp() as:
int icmp(const void *p1, const void *p2) {
int v1, v2;
v1 = *(int *) p1;
v2 = *(int *) p2;
if (v1 < v2) {
return -1;
} else if (v1 == v2) {
return 0;
} else {
return 1;
}
}
怎么了?我的版本也从 gcc 发出警告:
What's the deal? My version also throws a warning from gcc:
warning: passing argument 4 of 'qsort' from incompatible pointer type
但是,具有正确指针类型的 qsort 没有正确排序我的整数!这里很困惑.如果有人能启发我,我将不胜感激.
But, the qsort with the correct pointer type is not correctly sorting my ints! Very confused here. If anyone can enlighten me I will be very grateful.
推荐答案
如果你查看qsort
的原型,你会发现:
If you check the prototype of qsort
, you'll find:
void qsort (void* base, size_t num, size_t size,
int (*compar)(const void*,const void*));
如您所见,compar
函数的参数类型是 const void *
.
The parameter type of the compar
function is const void *
as you noticed.
- 它是
void *
因为qsort
应该对泛型类型进行排序,而不仅仅是int
.可以对double
数组、string
数组、struct
数组等进行排序. const void *
是为了避免意外更改指针指向的数据(在该compar
函数内).这只是关键字const
的典型安全措施.
- It's
void *
becauseqsort
is supposed to sort generic type, not justint
. You can sort array ofdouble
, array ofstring
, array ofstruct
, and so on. - It's
const void *
to avoid accidental changes to the data that the pointer is pointing to (within thatcompar
function). This is just a typical safety measure of the keywordconst
.
这篇关于qsort 比较:为什么 const void *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!