I'm writing a program which prompts the user to say how many elements an array should have, then fill that array with numbers:
int n;
int i;
float numbers[100];
printf("Enter number of elements:");
scanf("%d", &n);
for(i = 0; i < n - 1; i++)
scanf("%f\n", &numbers[i]);
I'm trying to write a function which takes that array of numbers, and sorts it in ascending order. I read somewhere online that there's actually a built in function in C that does this - qsort(). Here's my code:
void sort(int n, float array[])
{
int i;
int cmpfunc (const void * a, const void * b)
{
return(*(int*)a - *(int*)b );
}
qsort(array, n, sizeof(float), cmpfunc);
for(i = 1; i <= n; i++)
printf("%.2f\n", array[i]);
}
Basically the problem is I don't think I'm implementing the function correctly. For example, I'll run the program, set the array size to 5, and input the following numbers:
1,9,2,8,5
The output I get is:
1,2,8,9,0
There is a similar pattern in all my outputs.
It sorts it somewhat decently, except it always ends with a 0, and for some unknown reason, randomly skips one number of the array and doesn't sort it (in the example above 5 is skipped). In the for loop, I had i set to 0, but then my output would also skip a number when sorting, and it would still have a 0, except this time it would be at the beginning of the output.
Finally, it should be noted that I have absolutely no idea how the qsort() function works, or why it needs that other compare function to work, I just sort of copy pasted it in there.
If anyone knows the answer to my problem please help me out I'd really appreciate it, thank you.
for(i = 1; i <= n; i++)looks like an off-by-one.float, so the pointers passed to the comparison function point tofloatvalues, notintvalues.floattoint*doesn't look like a good idea.for(i = 0; i < n - 1; i++)should befor(i = 0; i < n ; i++), andfor(i = 1; i <= n; i++)should befor(i = 0; i < n; i++).