I'm just doing some extra work on my own to try and get a better grasp of multi dimensional string arrays in C, for example array[3][5]= {"apple","house","truck"}. I have a test file filled with many words with varying length, and want to fill the string array with these different words.I've used dynamic allocation to provide memory space, open the file, and the use fgets to get each word off because each word is on a new line. I save the word into a new place in the array, and then print it to check if it has saved. The words print like they should, which makes me believe that they are being stored, but then i get a seg fault. Can anyone explain to me why this is happening?
A sample of the text file and the form I have it in is(without the blank lines between words:
enchantment
enchantress
enchants
misusing
Mitch
Mitchell
miter
mitigate
mitigated
mitigates
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORDS 50
#define LETTERS 15
int main(int argc, char *argv[]) {
int i;
char **array;
FILE *file1;
char string[15];
array=(char **)malloc(LETTERS*sizeof(char*));
for (i=0;i<WORDS;i++) {
array[i]=(char *)malloc(LETTERS*sizeof(char));
}
if (argc != 2) {
printf("\nERROR: Wrong number of arguments entered\n");
return -1;
}
file1=fopen(argv[1],"r");
if (file1==NULL) {
printf("\nERROR: File 1 not found\n");
return -1;
}
for (i=0;i<=WORDS;i++) {
fgets(string,LETTERS,file1);
array[i][0]=*string;
printf("%s",string);
}
return 0;
}