Hello,
I am trying to get the following code to print out the number of days in each month using pointers.
This what the program currently prints:
Enter a year (ex. 1997): 2001
Year entered: 2001
--Not a Leap Year!--
Number of days in each month:
January: 0
February: 0
March: 0
April: 0
May: 0
June: 0
July: 0
August: 0
September: 0
October: 0
November: 0
December: 0
I am still trying to get my head around pointers so any help would be really appreciated. Thank you
Code:
#include <stdlib.h>
#include <stdio.h>
static int get_days_in_month(int **days, int year) ;
int main(int argc, char **argv) {
int nFields ;
int year = 0 ;
int days[12] ;
char *months[12] = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December"} ;
/* Get user year */
printf("Enter a year (ex. 1997): " ) ;
nFields = scanf("%d", &year) ;
/* Verify letters were not entered */
if (nFields == 0) {
printf("Incorrect Input\n") ;
return 0 ;
}
/* Call function */
days[12] = get_days_in_month(days, year) ;
/* Print months with # of days */
printf("Number of days in each month: \n") ;
for (int i = 0 ; i < 12 ; i++) {
printf("%10s: %2d\n", months[i], days[i]) ;
}
return EXIT_SUCCESS;
}
static int get_days_in_month(int **days, int year) {
days = malloc(sizeof(int) * 12) ;
/* number of days in each month excluding February */
days[0] = 31 ;
days[2] = 31 ;
days[3] = 30 ;
days[4] = 31 ;
days[5] = 30 ;
days[6] = 31 ;
days[7] = 31 ;
days[8] = 30 ;
days[9] = 31 ;
days[10] = 30 ;
days[11] = 31 ;
printf("Year entered: %d\n", year) ;
/* Leap Year found */
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
printf("\n--Leap Year!!--\n\n") ;
days[1] = 29 ;
} else { /* Not a Leap Year */
printf("\n--Not a Leap Year!--\n\n") ;
days[1] = 28 ;
}
return days ;
}