0

Im trying to read a file into a struct which contains a char array as shown in the code below, however it gives an output of segmentation fault: 11. I have tried everything including using similar examples but it has done my head in.

My code is as below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 1024

struct Raw_Word{
    char word[MAX_LENGTH];
    char filename [25];
    int length;
};

struct Final_Word{
    char word[MAX_LENGTH];
    int length;
    int amount;
};

struct Raw_Word raw_word[MAX_LENGTH];

int main(int argc, char* argv[]) {
if (argc > 10) {
        printf("Maximum of 10 files allowed");
        return 1;
    }

    int i = 0;
    int lines = 0;


    for (i = 1; i <= argc; i++) {
        FILE *fp = fopen(argv[i], "r");
while(fgets(raw_word[lines].word, MAX_LENGTH, fp)){
            //printf("%s", raw_word[lines].word);
        }
        fclose(fp);

    }

    for(int j = 0; j < lines; j++){
        printf("%s\n", raw_word[j].word);
    }

return 0;
}
  • 3
    As a general note, one of the best ways to find things like this is to first work out what line is causing the error. This can be done by putting in print statements or with [gdb](http://stackoverflow.com/questions/2069367/how-to-debug-using-gdb). – TheOmegaPostulate Dec 16 '14 at 22:35

1 Answers1

4

The line

for (i = 1; i <= argc; i++) 

is not right. You need to stop the index at argc-1.

for (i = 1; i < argc; i++) 

or

for (i = 1; i != argc; i++) 
R Sahu
  • 204,454
  • 14
  • 159
  • 270