I am working on a c program to read from a txt file and sort the strings.
data.txt:
jk ef ab cd bc gh fg ij hi de
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
int cmp(const void *p1, const void *p2) {
return strcmp(*(const char **)p1, *(const char **)p2);
}
int main() {
FILE *f = fopen("data.txt", "r");
char s[255][255];
char tmp[255];
int n = 0;
while (!feof(f)) {
fscanf(f, "%s", tmp);
strcpy(s[n], tmp);
n++;
}
fclose(f);
qsort(s, n, sizeof(char *), cmp);
int i = 0;
for (; i < n; i++) {
printf("%s ", s[i]);
}
return EXIT_SUCCESS;
}
I ran the code on Ubuntu and it breaks on a segfault. Believe this segfault happened in qsort and I could not figure out why.
Anyone can give me some suggestions?
The comparison function is incorrect, as you are sorting an array of arrays of
char, you can pass the pointers to the elements tostrcmpdirectly:Note however that your parsing loop is also incorrect:
feof()is not the correct way to check for end of file. Use this instead:The
qsortinvokation should specify the size of the array element:Here is a corrected version: