I need to put the names separated by commas from the text into struct that expands dynamically, but I am prohibited from using realloc ().I'm getting a core dumped error in this code. What is the error in this code?
#include <stdio.h> #include <stdlib.h> #include <string.h> struct movie{ double budget; int genre; char* name; double score; int year; }; void recorder_function(struct movie *movies){ FILE*fp; fp=fopen("Movies.txt","r"); struct movie *p; int i,n=0; char line[1000]; char temp_budget[50]; char temp_name[50]; char temp_genre[50]; while (!feof(fp)) { fgets(line,1000,fp); sscanf(line,"%50[^,],%50[^,],%50[^,]",temp_budget,temp_genre,temp_name); //I open the fields in this section movies=(struct movie *)calloc(n+1,sizeof(struct movie)); p=(struct movie *)calloc(n+1,sizeof(struct movie)); p[n].name=(char*)malloc(sizeof(char)*(strlen(temp_name)+1)); movies[n].name=(char*)malloc(sizeof(char)*(strlen(temp_name)+1)); for(i=0;i<n;i++) movies[i]=p[i]; strcpy(movies[n].name,temp_name); free(p); p=movies; n++; } for(i=0;i<n;i++) printf("%s\n",movies[i].name); } int main(){ int choice; struct movie *movies; recorder_function(movies); }
while (!feof(fp)) {?realloc(), you have to read the file twice. First to get the number lines so you can allocate themoviesarray the proper size. Then the second time to fill it in.recorder_function()takemoviesas a parameter? It immediately overwrites it withcalloc().moviesandpin the loop?