I'm trying to read some strings from a file, and copy them into a string array. I can't understand why I manage to read properly just the first of the strings in the file, before getting a segmentation fault. I know that each string in the file has up to 50 characters.
...
int i = 0;
char s[50];
int N=0;
FILE *fp;
//Figures out how many strings are stored in the file
while(fgets(s, 50, fp)!=NULL){N++}
rewind(fp);
char *strings[N]; //This is the array where I want to store strings
for(i=0;i<N;i++){
fgets(s, 50, fp);
strcpy(strings[i], s);
printf("%s", s );
}
Why I can't store succesfully strings into the array ?
You are making two mistakes:
1- when copying strings, you have to allocate memory for the destination, inyour case the destination is strings[i] for which you haven't allocated any memory
2-your strings must be null terminated
This code should work:
#define MAX_STRINGS 100
int i = 0;
char s[50];
int N=0;
while(fgets(s, 50, fp)!=NULL){N++;}
char strings[MAX_STRINGS][50];
rewind(fp);
for(i=0;i<N && i<MAX_STRINGS;i++){
fgets(s, 50, fp);
strcpy(strings[i], s);
printf("%s", s );
}
Note that if you are not using vectors, you have to pre-define the size of your array, basically the size of the array must be a constant
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.