0
#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?

1
  • strs[i]= array; -> strs[i]= strdup(array); If there is no strdup use malloc/memcpy to get the same. Here all the pointers point to array and that array contains six at last. Commented Mar 3, 2018 at 7:40

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

1 Comment

This invokes undefined behavior. You're using an indeterminate pointer for the target of a strcpy(). char strs[6][100], or use dynamic allocation to address this. It's still begging for a buffer overflow, but at least it won't be UB from inception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.