thank you so much in advance, so I try to print a calendar on a specific month and year with C programming, but I do not know why the string function of getMonthName does not work and caused a code dumped. I am not sure what is wrong and get confused between char*monthName and char monthName[25].
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
void printCalendar(int, int);
void printTitle(int, int);
void printBody(int, int);
const char*getMonthName(int);
int get_first_day(int, int);
int get_total_day_in_month(int, int);
int get_total_day(int, int);
bool is_leap_year(int);
int main() {
int year;
int month;
printf("Enter the month: ");
scanf("%d", &month);
printf("Enter the year: ");
scanf("%d", &year);
printf("\n");
printCalendar(month, year);
}
void printCalendar(int month, int year) {
printTitle(month, year);
printBody(month, year);
}
void printTitle(int month, int year) {
char*month_name;
strcpy(month_name, getMonthName(month));
printf("\t%s %d\n", month_name, year);
printf("----------------------------\n");
printf(" Sun Mon Tue Wed Thu Fri Sat\n");
}
const char*getMonthName(int month) {
char*month_name = "";
switch (month) {
case 1: strcpy(month_name, "January"); break;
case 2: strcpy(month_name, "February"); break;
case 3: strcpy(month_name, "March"); break;
case 4: strcpy(month_name, "April"); break;
case 5: strcpy(month_name, "May"); break;
case 6: strcpy(month_name, "June"); break;
case 7: strcpy(month_name, "July"); break;
case 8: strcpy(month_name, "August"); break;
case 9: strcpy(month_name, "September"); break;
case 10: strcpy(month_name, "October"); break;
case 11: strcpy(month_name, "November"); break;
case 12: strcpy(month_name, "December"); break;
}
return month_name;
}
void printBody(int month, int year) {
int first_day = get_first_day(month, year);
int total_day_in_month = get_total_day_in_month(month, year);
for (int i = 0; i < first_day; i++) {
printf(" ");
}
for (int i = 1; i <= total_day_in_month; i++) {
printf("%4d", i);
if ((i + first_day) % 7 == 0) {
printf("\n");
}
}
}
int get_first_day(int month, int year) {
const int Jan_1800 = 3;
int total_day = get_total_day(month, year);
return (Jan_1800 + total_day) % 7;
}
int get_total_day(int month, int year) {
int total = 0;
for (int i = 1800; i < year; i++) {
if (is_leap_year(year)) {
total += 366;
}
else {
total += 365;
}
}
for (int i = 1; i < month; i++) {
total += get_total_day_in_month(i, year);
}
return total;
}
int get_total_day_in_month(int month, int year) {
int day = 0;
switch (day) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = 31; break;
case 2: {
if (is_leap_year(year)) {
day = 29;
}
else {
day = 28;
}
}; break;
case 4: case 6: case 9: case 11: day = 30; break;
}
return day;
}
bool is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 != 0);
}
[https://onlinegdb.com/i0_F2XEwx][1]