Question

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;

}

No correct solution

OTHER TIPS

From your example, you need to allocate at least 6 chars for each of those strings, or you'll be dropping the terminal null character.

Dynamic memory allocation were wrong in your code.

Instead of this code array=(char **)malloc(LETTERS*sizeof(char*)); replace the following code

array=(char **)malloc(WORDS*sizeof(char *));
for(i=0;i<WORDS;i++)
array[i]=(char *)malloc(LETTERS*sizeof(char));

Reading the data from the file also you need to modify.

Instead of this code for (i=0;i<=WORDS;i++) { fgets(string,LETTERS,file1); array[i][0]=*string; printf("%s",string); }

replace the following code

i=0;
while(fgets(string,LETTERS,file1)!=NULL){
strcpy(array[i],string);
printf("%s",string);
i++;
}

Now i holds the value of total string read from the file. For printing the content of array

int j;
for(j=0;j<i;j++)
printf("%s",array[j]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top