In the above program, I create an array of pointers to char using malloc and then attempt to sort those "strings" using qsort. I'm getting incorrect results. More importantly, I'm getting different results every time I run the program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 1000
#define MAXCHARS 1000
int ballin_compare(const void *, const void *);
int main(int argc, char *argv[]){
char *linebuffer, **pointbuffer;
FILE *fp;
int i = 0;
if(argc < 2 || (fp = fopen(argv[1], "r")) == NULL)
return 1;
linebuffer = (char *)malloc(MAXCHARS);
pointbuffer = (char **)malloc(sizeof(char *) * MAXLINE);
while(i < MAXLINE && fgets(linebuffer, MAXCHARS, fp) != NULL){
pointbuffer[i] = (char *)malloc(strlen(linebuffer));
strcpy(pointbuffer[i++], linebuffer);
}
free(linebuffer);
qsort(pointbuffer, i, sizeof(char *), ballin_compare);
fclose(fp);
if((fp = fopen(argv[1], "w")) == NULL)
return 1;
int x;
for(x = 0; x < i; x++)
fputs(pointbuffer[x], fp);
fclose(fp);
printf("%s sorted successfully", argv[1]);
return 0;
}
int ballin_compare(const void *c, const void *d){
char *a = (char *)c;
char *b = (char *)d;
int i = 0;
while(a[i] && b[i] && a[i] == b[i])
i++;
if(a[i] < b[i])
return -1;
if(a[i] > b[i])
return 1;
return 0;
}
My guess is that I messed up my strcmp equivalent. Any ideas where my comparisons went wrong?