如何更新结构
结构其实就是把一组绑在一起的变量当成一条数据处理。你已经学会了创建结构对象,并使用“点表示法”访问结构的值,那么怎样修改结构中已经存在的某个值呢?可以像修改变量那样修改字段:
既然如此,你应该能分析出下面这段代码做了什么。
#include <stdio.h>
typedef struct {
const char *name;
const char *species;
int age;
} turtle;
void happy_birthday(turtle t)
{
t.age = t.age + 1;
printf("Happy Birthday %s! You are now %i years old!\n", t.name, t.age);
}
int main()
{
turtle myrtle = {"Myrtle", "Leatherback sea turtle", 99};
happy_birthday(myrtle);
printf("%s's age is now %i\n", myrtle.name, myrtle.age);
return 0;
}
但奇怪的事情发生了……
试驾
你编译并运行了代码,结果如下。
奇怪的事情发生了。
这段代码创建了一个新的结构,然后把它传给了一个函数,按理说,函数会将结构中某个字段的值递增1,但程序却……。
你知道age
字段在happy_birthday()
函数中更新了,因为printf()
函数显示了递增以后age
的值,但奇怪的是,虽然happy_birthday()
更新了age
,但程序返回main()
函数以后,age
又变回了原来的值。
脑力风暴
代码的行为十分诡异,但你已经掌握了足够多的信息,应该能推测到底发生了什么,是吧?