choptxen
choptxen

Reputation: 57

Array of pointers and file I/O in C

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *strs[6], array[100];
    int i;
    FILE *file  = fopen("random.txt", "r");

    for (i=0 ; i<6; i++)
    {
        fscanf(file ,"%s", array);
        strs[i]= array;

        printf("%s ", strs[i]);
    }

    printf("%s", strs[3]);

    return 0;
}

Inside the random.txt:

one two three four five six

Output is: one two three four five six six

My question is why the last one 'six', I cannot access third element that is 'four'. Why doesn not record them in char array of pointers?

Upvotes: 0

Views: 109

Answers (2)

4386427
4386427

Reputation: 44274

The problem is that all element in your array of pointers, i.e. strs, points to array. In other words - strs[0] points to array, strs[1] points to array, strs[2] points to array and so on.

So when you change array all elements in strs points to the new value.

It can be fixed in several ways but the easiest way is:

//char *strs[6], array[100];
char strs[6][100];

and

// fscanf(file ,"%s", array);
// strs[i]= array;
fscanf(file ,"%s", strs[i]);

However, notice that your code has no check for buffer overflow (which is bad). I'll recommend that you read about fgets

Upvotes: 3

Udayraj Deshmukh
Udayraj Deshmukh

Reputation: 1914

You shall use strcpy from string.h library

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char strs[6][100] , array[100];
    int i;
    FILE *file  = fopen("random.txt", "r");

    for (i=0 ; i<6; i++)
    {
        fscanf(file ,"%s", array);
        strcpy(strs[i], array) ;

        printf("%s ", strs[i]);
    }

    printf("%s", strs[3]);

    return 0;
}

Upvotes: 0

Related Questions