When I am executing printf command for level->description, the program gives me segmentation fault. I don't know why. Should I use malloc to repair it? The content (only 1 line ending with '\n') of file sokoban.dat is "chicago;addie;story begins here;-----#####-----------|-----#@$.#-----------|-----#####-----------"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
char *name;
char *description;
char *password;
char *map;
struct level *next;
//char *solution;
} LEVEL;
LEVEL* parse_level(char *line) { //parsing from file into the structure
LEVEL level;
char level_name[50];
char level_password[50];
char level_description[100];
char level_map[200];
int i = 0;
int j = 0;
while (line[i] != ';') { //getting level name
level_name[j] = line[i];
i++;
j++;
}
level_name[j]='\0';
level.name=&level_name[0];
//strcpy(&level.name,level_name);
//printf("%s\n",level.name);
printf("%s\n",level_name);
j = 0;
i++;
while (line[i] != ';') { //getting level password
level_password[j] = line[i];
i++;
j++;
}
level_password[j]='\0';
level.password=&level_password[0];
printf("%s\n",level_password);
j = 0;
i++;
while (line[i] != ';') { //getting level description
level_description[j] = line[i];
i++;
j++;
}
level_description[j]='\0';
level.description=&level_description[0];
printf("%s\n",level_description);
j = 0;
i++;
while (line[i] != '\n') { //getting level map
level_map[j] = line[i];
i++;
j++;
}
level_map[j]='\0';
level.map=&level_map[0];
printf("%s\n",level_map);
j = 0;
level.next=NULL;
LEVEL* levelPointer=&level;
return levelPointer;
}
int main(){
FILE *fp = fopen("sokoban.dat", "r");
if( fp == NULL ){
printf("No such file\n");
return 1;
}
char line[500];
//strcpy(line,"");
char c;
int i=0;
while((c = fgetc(fp)) != '\n'){ //reading from file 1 by 1 character
line[i]=c;
i++;
}
printf("%s\n",line);
LEVEL* level;
level=parse_level(line);
//printf("%s\n",level->description); **//!!! this is where error occur**
printf("%s\n",level->map);
return 0;
}