-
Qsort help needed
Hey I'm writing this program that is supposed to take a file with random numbers in it, and sort it in ascending order. I can't figure out how to get the qsort right because right now all my program does is print the numbers. Here's my code:
Code:
#include <stdio.h>
#include <stdlib.h>
int compare (const void * a, const void * b);
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main(){
char values[500];
char buffer[500];
int size = 100;
int i = 0;
int n;
FILE *fp;
fp = fopen("nums.bin", "r");
while(fgets(buffer, size, fp) != NULL)
{
values[i] = (int)buffer;
i++;
}
qsort(values, 4, sizeof(int), compare);
for (n=0; n<sizeof(values); n++){
printf("%d ", values[n]);
}
return 0;
}
-
Code:
int compare (const void * a, const void * b);
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
You only need the prototype if the actual function comes after main (or wherever you call it from).
Code:
char values[500];
char buffer[500];
You declare these as char arrays, but compare and sort integers. Pick one type (probably ints) and stick with it.
Code:
fp = fopen("nums.bin", "r");
Check if fopen failed (fp is NULL) before reading from it. If it's NULL, print an error with perror and exit your program.
Code:
while(fgets(buffer, size, fp) != NULL)
{
values[i] = (int)buffer;
i++;
}
fgets is for text. If nums.bin is binary, as the file extension suggests, you need to use fread instead of fgets. Also, values[i] = (int)buffer assigns every spot in values to contain the address of buffer. fread can read an integer directly into values[i], and if you use fgets, look into sscanf for converting the line of text to ints.
Code:
qsort(values, 4, sizeof(int), compare);
You're telling it to only sort 4 elements. Also, again, you're using sizeof(int), but values is a char array.
Code:
for (n=0; n<sizeof(values); n++){
printf("%d ", values[n]);
}
sizeof(values) will not give you what you want if you convert those arrays to ints (it only works for a char array by virtue of the fact that a char always has a size of 1). You need to give it the number of elements, not the number of bytes all the elements take up.
-
Apart fom all anduril462 said, your comparison function is wrong. You're telling it that those void pointers point to ints, but they don't, they point to chars. On platforms that don't allow misaligned reads, that code is going to crash.
Your best bet is to read the documentation about the qsort function: qsort - C++ Reference