Urgent help please

Runtime Error :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void Movie::show_movie(int k){
    system("cls");
    struct detail *mv;
    FILE *f;
    int n;
    f = fopen("data.dat","ab+");
    fseek(f,0,SEEK_END);
    n=ftell(f)/sizeof(detail);
    mv = new detail[n];
    fseek(f,0,SEEK_SET);
    fread((char*)&mv, sizeof(detail), n, f);  //I think the error occurs here
    fclose(f);
    cout << "\n\n\t\t\tName\t\t\tStart On\t\t\tStart At";
    for(int i=0; i<n; i++)
    cout<<"\n\n\t\t"<<mv[i].name<<"\t\t\t"<<mv[i].start_date<<"/"<<mv[i].start_month<<"/"<< mv[i].start_year<<"\t\t\t"<<mv[i].start_hour<<":00 - "<<mv[i].end_hour<< ":00";
    cout << endl << endl;
    delete[] mv;
    cout << "Press any key to return to previous menu...";
    getch();
    cout << endl << endl;
    if(k==0) movie_menu();
    if(k==1) admin_menu();
}
what is the file size?
I have solved the problem by reading the structure 1 by 1 instead of reading whole n structure. :)
But couldn't we read them all at once?
But couldn't we read them all at once?
Yes, but you need to provide the correct size. On line 11 you provide the size for a single object.
Yes, but you need to provide the correct size. On line 11 you provide the size for a single object.

I think the code is correct in that respect. The fread() is reading n objects of size sizeof(detail).

But it's reading it into the wrong place:
1
2
3
4
5
struct detail *mv;
...
mv = new detail[n];
...
fread((char*)&mv, sizeof(detail), n, f);  //I think the error occurs here 


The fread is storing the data at mv's address. In other words, it's overwriting the pointer itself (and a whole lot more). You want to store the data in the location that mv points to:
 
fread(mv, sizeof(detail), n, f);

No need to cast to a char* since fread expects a void* as its first argument and any pointer will cast automatically to void*
Topic archived. No new replies allowed.