结构作为参数的函数
- 整个结构可以作为参数传入函数
- 这时是在函数中新建了一个结构变量,并复制调用这个结构的值(重点,只是把值传入函数,而函数外面真正的变量并没有改变,与数组不同)
- 函数也可以返回一个结构
直接来个简单的例子吧:
问题:用户输入今天的日期,输出明天的日期。
提示:闰年,每个月最后一天,
代码:
#include <stdio.h>
#include <stdbool.h>/* 根据今天的日期算出明天的日期。*/
//结构体放在函数外侧,相当于一个全局变量,所有的函数都能使用。
struct date{ int month; int day; int year; }; //记住这个分号
bool is_leap(struct date d); //判断是否为闰年
int numbersofdays(struct date d); //给出这个月的天数
int main(int argc, char const *argv[])
{ struct date today; //定义两个结构体变量 struct date tomorrow; int days; int flag=1; //实现输入控制printf("请输入今天的日期(9-24-2012):");
scanf("%i-%i-%i",&today.month,&today.day,&today.year);days = numbersofdays(today);
tomorrow = today; //可以像一般变量一样赋值 if(today.day<days && today.month <=12){ tomorrow.day = today.day + 1; }else if(today.day == days && today.month <12){ tomorrow.day = 1; tomorrow.month +=1; }else if(today.day == days && today.month == 12){ tomorrow.day =1; tomorrow.month =1; tomorrow.year+=1; }else{ flag = 0; printf("输入有误!"); }if(flag){
printf("明天的日期是:"); printf("%i-%i-%i\n",tomorrow.month,tomorrow.day,tomorrow.year); }return 0;
}bool is_leap(struct date d)
{ bool is = false; if((d.year%4==0 && d.year%100!=0) || d.year%400==0) is = true; return is;} int numbersofdays(struct date d){ int days; int dayspermonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; if(d.month==2 && is_leap(d)) { days = 29; } else{
days = dayspermonth[d.month-1]; }return days;
}