When I use qsort() in the C on my Mac, these code works well, It can sort every lines in one file well.
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)){
//printf("%s",buf[i]);
i++;
}
qsort(buf, i, sizeof(buf[0]), compare);
}
However, when I use malloc to assign the space, it sucks. Why is that? The code below shows I use malloc to make one two-dimension array. I print the content of buf before and after. It seems that lose all the information.
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]);
}
output:
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 important, how to fix my malloc version?
char buf[][]
is an array of arrays of type char,char **buf
is a pointer to a pointer to type char.(the values are not guaranteed to be contiguous in memory) – Warder