Kavindu Vindika
Kavindu Vindika

Reputation: 2737

Same value written to the array when a text file read

I tried to read a text file into an array using following code, but each and every value of the array gets the final line read from the text file.

 #include <stdio.h>

int main()
{
    char line[255];
    char *kernal[3];

    FILE *fpointer_1 = fopen("sample.txt", "r");

    for (int i = 0; i <= 2; i++)
    {
        fgets(line, 255, fpointer_1);

        kernal[i] = line;
    };

    fclose(fpointer_1);

    printf("1st value : %s\n", kernal[0]);
    printf("2nd value : %s\n", kernal[1]);
    printf("3rd value : %s\n", kernal[2]);
    return 0;
}

Can anyone tell me why that happens and how to solve the issue ?

Upvotes: 0

Views: 43

Answers (1)

Youssef13
Youssef13

Reputation: 4994

The problem lies in the kernal[i] = line line. You always point to the same line. You need to allocate it a memory, then use strcpy to copy the contents from the line array to the new allocated memory.

kernal[i] = malloc(strlen(line) + 1);
strcpy(kernal[i], line];

Upvotes: 2

Related Questions