Reputation: 57
#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
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
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