Click to See Complete Forum and Search --> : about c function?


Serene
09-19-2001, 05:38 AM
I have a question about function qsort(void *base ,size_t number_of_entries,size element_width, int(*compare)(const void *,const void *))---the prototype ,but in the example like qsort(*,*,*,(int(*)(const void *,const void *))compare_float );it should be like in the prototype .when I change it in order of prototype ,I couldnt compile the source! I search much help ,but I could find some about it!
does any1 know it and give me good explain,I will deeply appreciate him!!!
thankz.

pinoy
09-19-2001, 06:49 AM
huh? qsort basically takes an array which you need to specify the number of elements and the size of each element. You also need to specify a pointer to a compare function (see man page).


/* our compare function */
int compare_float(const void *arg1, const void *arg2)
{
float f1 = *((float*)arg1);
float f2 = *((float*)arg2);

if (f1 < f2) return -1;
if (f1 > f2) return 1;
return 0;
}

int main(void)
{
int i;
float fl[] = { 2.3, 5.3, 3.4, 2.5, 4.3 };

/* sort fl, 5 elements each sizeof(float) */
qsort(fl, 5, sizeof(float), &compare_float);

printf("Sorted\n");
for (i = 0; i < 5; i++)
printf("%f\n", fl[i]);
return 0;
}

sans-hubris
09-19-2001, 08:09 AM
Originally posted by pinoy:
<STRONG>
qsort(fl, 5, sizeof(float), compare_float);
</STRONG>
(slight correction to func. call, remember the name of the function, just like an array, is a pointer to the function itself.)

pinoy
09-19-2001, 05:18 PM
(slight correction to func. call, remember the name of the function, just like an array, is a pointer to the function itself.)


No. Having the address of operator is the same thing as not specifying it. ie. &func == func. It's not the same as an array at all.

char a[10];
a != &a;

Serene
09-19-2001, 09:05 PM
hi,thanz.I know in the example it use forced-type (int (*)(const void *,const void *)) .and function name is the entry of the function,if define (*p)(),(*p)()=functionname.