Search code examples
carraysfile-handlingfilehandle

How to scan string from file and store it on an array of strings (two-dimensional array)?


I am scanning a string from a file and storing it into an array of strings. When I compile my program, it does not produce any error but when I run it, it says Segmentation fault (core dumped). I know that the error is in the fscanf statement, but I can't figure out what's wrong.

My code looks like this:

 FILE    *stringsIn = fopen("strings.txt", "rt");
 char    *strings[INPUT_STRINGS];

    for (int i = 0; i < INPUT_STRINGS; i++)
            fscanf(stringsIn, "%s ", &strings[i][0]);

Solution

  • You have an array of pointers but you didn't allocate space for each string. In this case what you can do is preallocate a big enough buffer or read in a preallocated buffer, see how many characters were read and allocate a string of that size.

    FILE    *stringsIn = fopen("strings.txt", "rt");
    char    *strings[INPUT_STRINGS];
    
    for (int i = 0; i < INPUT_STRINGS; i++) {
       strings[i] = (char*)malloc(2048); //allocate a big enough buffer
       fscanf(stringsIn, "%2047s ", &strings[i][0]);
    }
    

    The second version is something like:

    FILE    *stringsIn = fopen("strings.txt", "rt");
    char    *strings[INPUT_STRINGS];
    char temp[2048];
    
    for (int i = 0; i < INPUT_STRINGS; i++) {
       fscanf(stringsIn, "%2047s ", &temp);
       size_t len = strlen(temp);
       strings[i] = (char*)malloc(len + 1);
       strncpy(strings[i], temp, len);
    }