Rewrite the routines
day_of_year
andmonth_day
with pointers instead of indexing.
The exercise is quite simple, this is the solution:
int day_of_year(unsigned int year, int month, int day) {
int leap, i;
leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if((month >= 1 && month <= 12) && ((day >= 1) && (day <= *(*(daytab + leap) + month)))) {
for(i = 1; i < month; i++) {
day += *(*(daytab + leap) + i);
}
return day;
}
return -1;
}
int month_day(unsigned int year, int yearday, int *pmonth, int *pday) {
int leap, i;
leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if((leap == 1 && (yearday >= 1 && yearday <= 366)) || (leap == 0 && (yearday >= 1 && yearday <= 365))) {
for(i = 1; yearday > *(*(daytab + leap) + i); i++) {
yearday -= *(*(daytab + leap) + i);
}
*pday = yearday;
*pmonth = i;
return 1;
}
return -1;
}
The expression (daytab + leap)
is a pointer to the leap
-th row and (*(daytab + leap) + i)
is a pointer to the i
-th element of the leap
-th row.