目录
1 结构体变量作函数参数
结构体变量可以像普通变量一样作为函数的参数。其内部运行也是传值不传参,即进入从main函数进入新函数后,新函数会再在内存中创造一个和传进来的结构体一模一样的结构体(地址不同),新函数会在新产生的结构体基础之上对其进行操作,而不会改变原结构体。例如下面的程序:
#include<stdio.h>
struct adate
{
int year;
int month;
int day;
};
void get_today(struct adate today)
{
printf("请按顺序输入年月日:\n");
scanf("%d",&today.year);
scanf("%d",&today.month);
scanf("%d",&today.day);
printf("get_today函数中的today是:%d年%d月%d日\n",today.year,today.month,today.day);
}
void main(void)
{
struct adate today={0,0,0};
get_today(today);
printf("原today是:%d年%d月%d日\n",today.year,today.month,today.day);
}
运行结果为:
请按顺序输入年月日:
2022
8
17
get_today函数中的today是:2022年8月17日
原today是:0年0月0日
由此可见,get_today函数并没有改变main函数中的today的值。要想实现值被函数改变的目的,有两种方法。
方法1:在函数中返回新构造的结构体
例如将上述代码中get_today函数增加一个struct adate返回值即可,代码如下所示:
#include<stdio.h>
struct adate
{
int year;
int month;
int day;
};
struct adate get_today(struct adate today)
{
printf("请按顺序输入年月日:\n");
scanf("%d",&today.year);
scanf("%d",&today.month);
scanf("%d",&today.day);
printf("get_today函数中的today是:%d年%d月%d日\n",today.year,today.month,today.day);
return today;
}
void main(void)
{
struct adate today={0,0,0};
today=get_today(today);
printf("原today是:%d年%d月%d日\n",today.year,today.month,today.day);
}
运行结果为:
请按顺序输入年月日:
2022
8
17
get_today函数中的today是:2022年8月17日
原today是:2022年8月17日
原today的值也被改变了。
方法2 将结构体指针作为函数参数
在函数中访问结构体变量参数成员用:指针变量名->运算符。代码如下所示:
#include<stdio.h>
struct adate
{
int year;
int month;
int day;
};
void get_today(struct adate *today)
{
printf("请按顺序输入年月日:\n");
scanf("%d",&today->year);
scanf("%d",&today->month);
scanf("%d",&today->day);
printf("get_today函数中的today是:%d年%d月%d日\n",today->year,today->month,today->day);
}
void main(void)
{
struct adate today={0,0,0};
get_today(&today);
printf("原today是:%d年%d月%d日\n",today.year,today.month,today.day);
}
运行结果如下:
请按顺序输入年月日:
2022
8
17
get_today函数中的today是:2022年8月17日
原today是:2022年8月17日
可知原today也被改变了。值得注意的是today(结构体变量指针)->day=today(结构体变量名).day,是他的成员变量,所以取址的话还要在前面加&。
2 结构体数组
结构体类型也可以像一般类型一样,定义成数组,数组的每一个元素都是一个结构体变量。代码如下:
#include<stdio.h>
void main(void)
{
struct adate
{
int year;
int month;
int day;
};
struct adate date[3]={{2022,8,17},{2022,8,18},{2022,8,19}};
printf("第1个元素为:%d年%d月%d日\n",date[0].year,date[0].month,date[0].day);
printf("第2个元素为:%d年%d月%d日\n",date[1].year,date[1].month,date[1].day);
printf("第3个元素为:%d年%d月%d日\n",date[2].year,date[2].month,date[2].day);
}
运行结果如下所示:
第1个元素为:2022年8月17日
第2个元素为:2022年8月18日
第3个元素为:2022年8月19日
3 结构体中的成员可以是任何数据类型,包括结构体
如下代码所示:
#include<stdio.h>
void main(void)
{
struct atime
{
int hour;
int min;
int sec;
};
struct adate
{
int year;
int month;
int day;
struct atime now;
};
struct adate today={2022,8,17,{17,6,54}};
struct adate *p=&today;
printf("%d年%d月%d日%d时%d分%d秒",p->year,p->month,p->day,p->now.hour,p->now.min,p->now.sec);
}
代码运行结果如下:
2022年8月17日17时6分54秒
注意用指针访问hour时,不能用p->now->hour,因为now是结构体而不是指针,p才是指针。