I am simply trying to read from a text file, parse some information into an "array of strings" and then alphabetize the array using qsort. However, I keep getting a segmentation fault during the sorting part. I am new to C, can anybody take a look at my code and tell me what the problem is?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int compare (const void * a, const void * b ) {
return strcmp(*(char **)a, *(char **)b);
}
int main(int argc, char* argv[]){
FILE *fp;
fp = fopen(argv[1], "r"); // argv[1] = "input.txt"
char allStrings[255][255];
int stringArrCounter = 0;
char buff[255]; /* String to put the scanned shit in*/
char blank[255];
strcpy(blank, " ");
int counter = 0;
while (!feof(fp)){
char stringer[255];
char stringer2[255];
fgets(buff, 255, fp);
if (strcmp(buff, blank) > 0){
if (counter % 5 == 0){
strncpy(stringer, buff, strlen(buff)-1);
}
else if (counter % 5 == 1){
strncat(stringer, buff, strlen(buff)-1);
}
else if (counter % 5 == 3){
strncpy(stringer2, buff, strlen(buff)-10);
strncat(stringer2, stringer, strlen(stringer));
}
else if (counter % 5 == 4){
strcpy(allStrings[stringArrCounter], stringer2);
printf("%s\n", stringer2);
memset(stringer,0,sizeof(stringer));
memset(stringer2,0,sizeof(stringer2));
stringArrCounter++;
}
counter++;
}
}
qsort(allStrings, 255, sizeof(char *), compare);
}