对于任意多的数,自动分配内存,然后进行排序,但是运行结果出现:
cannot convert from 'const void *' to 'const int *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
问题处于此处:【register int const *pa = a;】
求大神指导!!!
附上代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int compare_integers(void const *a, void const *b)
{
register int const *pa = a;
register int const *pb = b;
return *pa > *pb ? 1 : *pa < *pb ?-1 : 0;
}
int main()
{
int *array;
int n_values;
int i;
printf("how many numbers?");
if(scanf("%d",&n_values) != 1 || n_values <= 0){
printf("illegal number\n");
exit(EXIT_FAILURE);
}
array = (int *)malloc (n_values * sizeof(int));
if(array == NULL){
printf("can't get memory for that many numbers.\n");
exit(EXIT_FAILURE);
}
for(i=0;i<n_values;i++){
printf("?");
if(scanf("%d",array+i) != 1){
printf("error reading value #%d\n",i);
free(array);
exit(EXIT_FAILURE);
}
}
qsort(array,n_values,sizeof(int),compare_integers);
for(i=0;i<n_values;i++)
printf("%d\n",array[i]);
free(array);
return EXIT_SUCCESS;
}
register int const *pa = (int const *)a; register int const *pb = (int const *)b;
错误说很清楚了:
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
不能实现从 void* 到非void的自动转换,需要显式的强行转换,(没实现隐式的自动转换)
明白了,谢谢了。我是初学者,很荣幸向大神请教。
@aifuliwade: 遇到错误,关键要分析错误信息,有时错误信息很隐晦,有时却很直白,主要是直接错误就简单,有些错误是经过了“多道转手”,理解起来就很麻烦了,多调试就好了。