When I use qsort () in C on my Mac, this code works well, it can sort all the lines in one file.
int compare(const void *p, const void *q) { return strcmp(p,q); } void function_name(){ char buf[1024][1024]; int i=0; FILE * fp; if(!(fp=fopen(filename,"r"))){ perror("Open error!"); exit(0); } while(fgets(buf[i],1024,fp)){
However, when I use malloc to assign space, it sucks. Why is this? In the code below, I use malloc to create one two-dimensional array. I print the contents of the buffer before and after. All information seems to be losing.
int i=0; FILE * fp; char ** buf; buf = (char **)malloc(sizeof(char*)*1024); if(!(fp=fopen(filename,"r"))){ perror("Open error!"); exit(0); } buf[0]=(char *)malloc(sizeof(char)*1024); while(fgets(buf[i],1024,fp)){ i++; buf[i]=(char *)malloc(sizeof(char)*1024); } for(int j=0;j<i;j++){ printf("%s",buf[j]); } printf("hehe%ld\n",sizeof(char)*1024); qsort(buf, i, sizeof(char)*1024, compare); printf("hehe\n"); for(int j=0;j<i;j++){ printf("%s",buf[j]); }
exit:
a A b c d D C E e B d e f a hehe1024 hehe (null)(null)(null)(null)(null)(null)(null)(null)(null)(null)(null)(null)(null)(null)(null)(null)
Most importantly, how to fix my version of malloc?
c linux qsort
Weiheng Li 07 Sep '16 at 2:29 2016-09-07 02:29
source share