Reputation: 272
char *string[n];
for (int i = 0; i < n; i++) {
char string[60];
fscanf(fptr, "%s%*[^\n]", string);
strings[i] = string;
printf("%s\n", strings[i]);
}
puts("Ended");
for (int i = 0; i < n; i++) {
printf("%s\n", strings[i]);
This is part of my code in C ^. strings[]
contains pointers to the first word of each line in the file. So if my file contains:
ABC 123 DEF 123 GHI 123
I get the following output:
ABC DEF GHI Ended GHI GHI GHI
Which means there's nothing wrong with the initialisation. Then what is going on?
Upvotes: 1
Views: 70
Reputation: 909
When you wrote :
strings[i]=string
You were not copying the original string into the array because the “string” variable only contains a pointer (memory address) of the stack allocated string. When you go into the next iteration of the for loop, the stack allocated “string” variable gets freed/thrown away.
So your “strings” array contains pointers to unallocated memory. You should use “strcpy” instead. If the size of your “strings” array is not constant, use “malloc” then “strcpy”.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr = fopen("test.txt", "r");
char strings[10][60];
int n = 3;
for (int i = 0; i < n; i++)
{
char string[60];
fscanf(fptr, "%s%*[^\n]", string);
strcpy(strings[i], string);
printf("%s\n", strings[i]);
}
puts("Ended");
for (int i = 0; i < n; i++)
{
printf("%s\n", strings[i]);
}
}
Or, simpler:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr = fopen("test.txt", "r");
char strings[10][60];
int n = 3;
for (int i = 0; i < n; i++)
{
fscanf(fptr, "%s%*[^\n]", strings[i]);
printf("%s\n", strings[i]);
}
puts("Ended");
for (int i = 0; i < n; i++)
{
printf("%s\n", strings[i]);
}
}
Upvotes: 3