I am attempting to create a spell checking program that reads in a file containing ~3000 unordered 3-4 letter words which are on a line each, sorts them into alphabetical order and then prints them out.
I have a working version using "standard" array form, array[][], however I'm attempting to modify the program to use pointers only. I thought that by mallocing the array according to the size of char * the size of my file there would be enough memory for the program to execute correctly, however I keep getting SEGV when I run my code, pointing to my while loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void bubbleSortWordsArray(char **array, int wordCount, int arrSize);
void printWordsArray(char **array, int wordCount);
int numOfLines(FILE *filePoint);
int main(int argc, char **argv) {
FILE *fp = fopen(argv[1], "r");
int i = 0, size = numOfLines(fp);
char **words = (char **)malloc(sizeof(char) * size);
if (fp == NULL) {
fprintf(stderr, "fopen failed");
exit(EXIT_FAILURE);
}
while (fgets(words[i], size, fp)) {
words[i][strlen(words[i]) - 1] = '\0';
i++;
}
fclose(fp);
bubbleSortWordsArray(words, i, size);
printWordsArray(words, i);
free(words);
return (0);
}
void bubbleSortWordsArray(char **array, int wordCount, int arrSize)
{
int c;
int d;
char *swap = (char *)malloc(sizeof(char) * arrSize);
for (c = 0; c < (wordCount - 1); c++) {
for (d = 0; d < (wordCount - c - 1); d++) {
if (0 > strcmp(array[d], array[d + 1])) {
strcpy(swap, array[d]);
strcpy(array[d], array[d + 1]);
strcpy(array[d + 1], swap);
}
}
}
}
void printWordsArray(char **array, int wordCount)
{
int i;
printf("\n");
for (i = 0; i < wordCount; i++) {
printf("%s\n", array[i]);
}
}
int numOfLines(FILE *filePoint) {
int c, count;
count = 0;
for (;; ) {
c = fgetc(filePoint);
if (c == EOF)
break;
if (c == '\n')
++count;
}
rewind(filePoint);
return count+1;
}