Накорябал такой код. Вроде всё работает, память очищается, а вот структуру приходится создавать через левые значения переменных (struct date *today = date_create (1, 1, 1);). Как это правильно делается?
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct date
{
int year;
int month;
int day;
};
struct date *date_create(int year, int month, int day)
{
struct date *when = malloc(sizeof(struct date));
assert(when != NULL);
when->year = year;
when->month = month;
when->day = day;
return when;
}
void date_destroy(struct date *when)
{
assert(when != NULL);
free(when);
}
void date_print(struct date *when)
{
printf (" date is %i/%i/%i\n", when->year, when->month, when->day);
}
int main(void)
{
const int dayspermonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
struct date *today = date_create (1, 1, 1);
printf ("Enter today`s date yyyy mm dd:\n");
scanf ("%i %i %i", &today->year, &today->month, &today->day);
struct date *tomorrow = date_create (today->year, today->month, today->day);
if (today->day != dayspermonth[today->month - 1])
{
tomorrow->year = today->year;
tomorrow->month = today->month;
tomorrow->day = today->day + 1;
}
else if (today->month == 12)
{
tomorrow->year = today->year + 1;
tomorrow->month = 1;
tomorrow->day = 1;
}
else
{
tomorrow->year = today->year;
tomorrow->month = today->month + 1;
tomorrow->day = today->day;
}
date_print(today);
date_print(tomorrow);
date_destroy(today);
date_destroy(tomorrow);
return 0;
}