Tuesday, 15 July 2014

Segmentation error 11 when using struct arrays in c -



Segmentation error 11 when using struct arrays in c -

i working on project , have nail snag have spent hours trying figure out. i'm close right wrong in malloc of struct array. i'll post code below can see it. goal of function set read in film info saved in file , set info structure.

#include <stdio.h> #include <stdlib.h> #include "support.h" #include "scanner.h" #include <string.h> int counter(char *movierecords) { int count = 0; char *name; char *about; int date; int time; char *rate; char *ppl; char *dir; //printf("test"); file *fp = fopen(movierecords, "r"); //printf("gggg"); name = readstring(fp); while (!feof(fp)) { //printf("test in loop"); = readstring(fp); date = readint(fp); time = readint(fp); rate = readtoken(fp); ppl = readstring(fp); dir = readstring(fp); //printf("test read"); free(name); free(about); free(rate); free(ppl); free(dir); //printf("test free"); count++; name = readstring(fp); } //printf("test escape loop"); fclose(fp); //printf("test file close"); homecoming count; } film **readrecord(char *movierecords, int count) //mallocates space , reads info array of film structures { int x = 0; film **data1; file *fp = fopen(movierecords, "r"); data1 = malloc(sizeof(struct film *) * (count + 1)); //mallocate space struct array movies1 printf("another test"); while (x < count + 1) //loop mallocates space string variables in movies1 struct movies { data1[x]->moviename = malloc(sizeof(char) * 1001); data1[x]->description = malloc(sizeof(char) * 2001); data1[x]->rating = malloc(sizeof(char) * 10); data1[x]->cast = malloc(sizeof(char) * 512); data1[x]->director = malloc(sizeof(char) * 30); x++; } printf("test point3\n"); x = 0; while (!feof(fp)) { data1[x]->moviename = readstring(fp); data1[x]->description = readstring(fp); data1[x]->year = readint(fp); data1[x]->length = readint(fp); data1[x]->rating = readtoken(fp); data1[x]->cast = readstring(fp); data1[x]->director = readstring(fp); x++; } printf("test point4\n"); fclose(fp); homecoming data1; }

header file:

typedef struct entry { char *moviename; char *description; int year; int length; char *rating; char *cast; char *director; } movie; int counter(char *movierecords); film **readrecord(char *movierecords, int count);

main:

#include <stdio.h> #include <stdlib.h> #include "support.h" #include <string.h> int main (int argc, char **argv) { int count = 0; printf("%d", argc); film **data1; count = counter(argv[1]); printf("%d", count); printf("hello"); data1 = readrecord(argv[1], count); homecoming 0; }

you have allocate memory "data1[x]" because malloc(double pointer) allocate memory array of records(single pointer). fot single pointer data[x] have allocate memory

c arrays struct segmentation-fault

No comments:

Post a Comment