We've got the malloc() part working I think but now the program is crashing for the sort part where I need to sort the words from the text file (one word on a line) in length order. Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXWORDLENGTH 30
int compare(const void *a, const void *b);
int main(int argc, char *argv[]) {
FILE *fp;
int iNumWords = 0;
int i;
char word[MAXWORDLENGTH];
char *ptr[22];
if (argc == 2) {
fp = fopen(argv[1], "r");
while (!feof(fp)) {
fgets(word, MAXWORDLENGTH, fp);
iNumWords = iNumWords + 1;
}
fseek(fp, 0L, SEEK_SET);
printf("\nThe total number of words in %s is %d\n\n", argv[1], iNumWords - 1);
for (i = 0; i < iNumWords - 1; i++) {
fgets(word, MAXWORDLENGTH, fp);
ptr[i] = (char *)malloc(strlen(word) + 1);
strcpy(ptr[i], word);
}
fseek(fp, 0L, SEEK_SET);
for (i = 0; i < iNumWords - 1; i++) {
fgets(word, MAXWORDLENGTH, fp);
qsort(word, iNumWords - 1, MAXWORDLENGTH, compare);
}
fseek(fp, 0L, SEEK_SET);
for(i = 0; i < iNumWords - 1; i++) {
puts(ptr[i]);
free(ptr[i]);
}
}
fclose(fp);
system("PAUSE");
return 0;
}
int compare(const void *a, const void *b) {
int rc;
if (strlen(a) < strlen(b)) {
rc = -1;
}
else if (strlen(a) == strlen(b)) {
rc = 0;
}
else {
rc = 1;
}
return rc;
}
How can this problem be fixed? The logic and syntax looks correct but the program is crashing again and I believe it is happening during the sorting part of the program.