c - qsort() giving random results -
in above program, create array of pointers char using malloc , attempt sort "strings" using qsort. i'm getting incorrect results. more importantly, i'm getting different results every time run 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 = 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 = 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 messed strcmp equivalent. ideas comparisons went wrong?
the problem qsort
passes in pointers elements of array. since array elements of type char *
, comparison function receives char **
inputs. written, comparing addresses if strings, naturally results in nonsense results.
you should write
const char *a = *(const char **)c; const char *b = *(const char **)d;
in ballin_compare
.
Comments
Post a Comment