It’s a function that makes events based off the time values the user enters, it then converts the value to Unix Epoch using mktime and stores them to a file. I’ve tested and found that everything else works well until we reach the section where the user enters the values seems like I’m not using the pointer event to the struct tm well, so I need help in doing it right.
int EventCreator(){
FILE *fptr = fopen("Events_Calendar.txt", "a+");
struct tm *event;
printf("Enter the values of the hour minute day month year in digits and this specific format meaning using spaces to seperate them");
printf("\n hr min day mon yr\n>");
scanf("%d %d %d %d %d", event->tm_hour, event->tm_min, event->tm_mday, event->tm_mon, event->tm_year);
time_t NineteenEvent = mktime(event);
printf("%ld", NineteenEvent);
fprintf(fptr, "%ld\n", NineteenEvent);
fclose(fptr);
}
>Solution :
You have declared a pointer to a struct tm but you haven’t allocated memory for a struct tm. I suggest that you make event an automatic variable instead.
Example:
void EventCreator() { // make the function `void` since you do not return anything
FILE *fptr = fopen("Events_Calendar.txt", "a+");
if (fptr) { // check that opening the file succeeds
// `event` is now not a pointer and set `tm_isdst` to a negative value
// to make `mktime` guess if DST is in effect:
struct tm event = {.tm_isdst = -1};
printf(
"Enter the values of the hour minute day month year in digits and "
"this specific format meaning using spaces to seperate them\n"
"hr min day mon yr\n>");
// %d requires an `int*` but you've supplied it with `int`.
// (also, check that scanf succeeds)
if (scanf("%d %d %d %d %d", &event.tm_hour, &event.tm_min,
&event.tm_mday, &event.tm_mon, &event.tm_year) == 5) {
event.tm_year -= 1900; // years since 1900
--event.tm_mon; // 0-11
time_t NineteenEvent = mktime(&event); // take its address here
printf("%ld", NineteenEvent);
fprintf(fptr, "%ld\n", NineteenEvent);
fclose(fptr);
}
}
}