I have written this to test qsort. The array takes the values, but qsort isn't working in my code. I think that there may also be a problem with calloc, becasue I am able to enter more entries than supp;ied by calloc, what do you think?
Code:
/*A program that reads into an array created to hold x amount of ints, then order the array using qsort and finally print it out*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int compare_doubles(double *v1, double *v2);
int read_into_array(double[]);
void print_array(double[], int);
int
main(int argc, char **argv) {
double *array;
int n, i;
printf("Enter how many values to be stored in the array: ");
scanf("%d", &n);
array = calloc(n, sizeof(double));
for (i = 0; i < n; i++)
{
array[i]=0;
}
printf("Now put some values into the array to sort: ");
n = read_into_array(array);
qsort(array, n, sizeof(*array), compare_doubles);
print_array(array, n);
return 0;
}
int
compare_doubles (double *ptr1, double *ptr2) {
if (ptr1<ptr2)
{
return -1;
}
if (ptr1>ptr2)
{
return 1;
}
return 0;
}
int
read_into_array(double A[]) {
int cntr=0;
double number;
while (scanf("%lf", &number)==1)
{
A[cntr]=number;
cntr++;
}
return cntr;
}
void print_array(double A[], int n) {
int i;
for (i=0; i<n; i++) {
printf("%.3f ", A[i]);
}
printf("\n");
return;
}