Ali Haydar Kurban
Ali Haydar Kurban

Reputation: 38

Array of pointers for string while reading file in C

I want to read a file and store each line in the array of pointer. The file has 4 lines and each line has 4 characters. I read each line with using fgets and assign the line to my array of pointer. While assignmentation I can write the line correctly but after the loop(for reading file) the result is not correct. NUM_VOWELS is 4, MAX_SIZE is 20 and they are defined as macros

My main is :

int main(void)
{
    FILE *file_vowels;
    int i, line_count = 0;
    char *vowels[NUM_VOWELS]; // my array of pointer
    char line[MAX_SIZE], *status;

    file_vowels = fopen(FILE_VOWELS, "r");
    for(
        status = fgets(line, MAX_SIZE, file_vowels);
        status != NULL;
        status = fgets(line, MAX_SIZE, file_vowels)
        )
    {
        if(line[strlen(line) -1] == '\n')
            line[strlen(line) -1] = '\0';

        vowels[line_count] = line;
        printf("vowels[%d] : %s\n", line_count, vowels[line_count]);
        line_count++;

    }
    printf("=====================\n");

    for(i = 0; i < NUM_VOWELS; ++i)
        printf("vowels[%d] : %s\n", i, vowels[i]);

    return 0;
}

Here is the result :

enter image description here

Here is the example file :

enter image description here

Upvotes: 0

Views: 207

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38922

vowels[line_count] = line;

There is only one line array and you assign its address to vowels[line_count]. As a result each vowels[i] points line that contains the last read file line. Try

vowels[line_count] = strdup(line);

Don't forget free(vowels[i]) later.

Another solution

char vowels[NUM_VOWELS][MAX_SIZE];
...
strcpy(vowels[line_count], line);

Upvotes: 2

Related Questions