Click here to Skip to main content
15,867,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this function inserts a book info into structure .. it works well but when scanning the date the program crushes..I searched a lot but couldn't fix it

typedef struct
{
    char title[10];
    char author[10];
    char publisher[10];
    char ISBN[10];
    dateStruct* date;
    int copies;
    int current;
} book;
typedef struct
{
    int day;
    int month;
    int year;
} dateStruct;

book* insert(void)
{
   book* theInserted =(book*)malloc(1*sizeof(book));
   gets(theInserted->title);
   gets(theInserted->author);
   gets(theInserted->publisher);
   gets(theInserted->ISBN);
   scanf("%d%d",&(theInserted->copies),&(theInserted->current));
   scanf("%d%d%d",&(theInserted->date->day),&(theInserted->date->month),&(theInserted->date->year));
    return theInserted;
}


What I have tried:

this is where something goes wrong:

scanf("%d%d%d",&(theInserted->date->day),&(theInserted->date->month),&(theInserted->date->year));
Posted
Updated 29-Nov-17 21:04pm

1 solution

You must allocate memory for the theInserted->date and free it when no longer used:
book* theInserted =(book*)malloc(sizeof(book));
theInserted->date = (dateStruct*)malloc(sizeof(dateStruct));

/* Use theInserted here */

/* Free memory */
free(theInserted->date);
free(theInserted);
When not doing so, the theInserted->date member points to anywhere resulting in an access violation or just a program crash.

A better solution is to make the dateStruct member a normal type member and not a pointer:
typedef struct
{
    char title[10];
    char author[10];
    char publisher[10];
    char ISBN[10];
    dateStruct date; // normal member and not pointer
    int copies;
    int current;
} book;

/* ... */

scanf("%d%d%d",&(theInserted->date.day),&(theInserted->date.month),&(theInserted->date.year));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900