Search code examples
arrayscfile-iopass-by-referencepass-by-value

C Array elements all changing to the same value


I'm trying to populate an array of names using an input file, however the elements of my array all end up turning into the same value and I'm unsure why.

    char* names[name_count];

    for (int i = 0; i < name_count; i++) {
        names[i] = fgets(buffer, MAX_LINE_LENGTH, input_fp);
        for (int j = 0; j <= i; j++) {
            puts(names[j]);
        }
    }

The first line of the input file specifies how many names there are, and the assignment specified that we won't need to use dynamically allocated memory so I'm using a variable-sized array.

If I had 5 names and the last one was Ed, the result at the end of the for loop would be my array storing Ed in all the spots instead of Ed in the last spot and the rest of the names before it.


Solution

  • fgets() function returns the buffer passed.

    You are reusing the buffer, so the elements are set to the same pointers and the contents are overwritten.

    You should copy the strings to retain the contents.

    Using functions from stdlib.h (malloc) and string.h (strcpy):

            fgets(buffer, MAX_LINE_LENGTH, input_fp);
            names[j] = malloc(strlen(buffer) + 1); /* +1 for the terminating null character */
            if (names[j] == NULL) exit(99); /* check for allocation failure */
            strcpy(names[j], buffer);
    
    

    Or using a POSIX function (not in the C standard before C23) in string.h:

            names[i] = strdup(fgets(buffer, MAX_LINE_LENGTH, input_fp));