结构体定义方式
//第一种
struct date{int day;int month;int year};
struct date today,tomorrow;
//第二种
struct date{int day;int month;int year} today,tomorrow;
//第三种 没有名字的结构体变量
struct {int x;int y;} p1,p2;
//赋值
struct date{int day;int month;int year};
struct date today;
today=(struct date){7,2,2020};
struct date tomorrow={8,2,2020};
结构体测试程序
输入今天的日期,输出明天的日期
#include<stdio.h>
#include<stdbool.h>
struct date{
int day;
int month;
int year;
}; //声明
int main(int argc,char const* argv[])
{
struct date today;
struct date tomorrow;
scanf("%i-%i-%i",&today.day ,&today.month ,&today.year);//输入今天的日期
if(today.day !=lastday(today))//如果今天不是某个月的最后一天
{
tomorrow.day =today.day +1;
tomorrow.month =today.month ;
tomorrow.year =today.year ;}
else if(today.month ==12)//如果今天是一年的最后一天
{
tomorrow.day =1;
tomorrow.month =1;
tomorrow.year =today.year+1 ;}
else//
{
tomorrow.day =1;
tomorrow.month =today.month+1 ;
tomorrow.year =today.year ;}
printf("%i-%i-%i",tomorrow.day ,tomorrow.month ,tomorrow.year );
return 0;
}
bool leapyear(struct date d)//判断某一年是否是闰年
{
int y=d.year;
bool leap=false;
if((y%4==0&&y%100!=0)||y%400==0)
leap=true;
return leap;
}
int lastday(struct date d)
{
int days;
int dayspermonth[]={31,28,31,30,31,30,31,31,30,31,30,31};
if(d.month ==2&&leapyear(d))
days=29;
else
days=dayspermonth[d.month -1];
return days;
}
测试结果:
结构体及结构体指针当做函数参数
将用户输入的结构体当做参数,在子程序中显示结构体内容
将用户输入的结构体的指针当做参数,在子程序中显示结构体内容
#include<stdio.h>
struct date{
int day;
int month;
int year;
};
struct date* getstruct(struct date* d)//用指针的形式实现输入结构体
{
scanf("%d",&d->day);//& (*d).day 赋值操作
scanf("%d",&d->month);
scanf("%d",&d->year);
return d; //返回一个指针
}
void outstruct(struct date p)
{
printf("%d-%d-%d\n",p.day ,p.month ,p.year );
}
void output(const struct date* q )
{
printf("%d-%d-%d",q->day ,q->month ,q->year );//q->day 相当于(*q).day
}
int main(int argc,char const* argv[])
{
struct date day={
0,0,0
};
struct date* d;
d=getstruct(&day);//返回的是指针
outstruct(day);
outstruct(*d);//用*提取指针所指的内容
output(d);//把指针当做参数传给output
}
结构体数组及嵌套结构体
#include<stdio.h>
struct date{ //出生年月
int day;
int month;
int year;
};
struct data{ //个人信息
char name;
char gender;
struct date birth;//出生年月结构体嵌套进来
};
void printdata(struct data m[])
{
int i;
for(i=0;i<2;i++)
{
printf("%c %c %d-%d-%d\n",m[i].name,m[i].gender,m[i].birth.day ,m[i].birth.month ,m[i].birth.year );
}
}
int main(int argc,char const* argv[])
{
struct data members[]={ //包含两个人信息的数组
{'A','M',{1,1,1996}},
{'B','W',{1,8,1997}}
};
printdata(members); //显示
}