如何更新结构

结构其实就是把一组绑在一起的变量当成一条数据处理。你已经学会了创建结构对象,并使用“点表示法”访问结构的值,那么怎样修改结构中已经存在的某个值呢?可以像修改变量那样修改字段:

如何更新结构 - 图1

既然如此,你应该能分析出下面这段代码做了什么。

  1. #include <stdio.h>
  2. typedef struct {
  3. const char *name;
  4. const char *species;
  5. int age;
  6. } turtle;
  7. void happy_birthday(turtle t)
  8. {
  9. t.age = t.age + 1;
  10. printf("Happy Birthday %s! You are now %i years old!\n", t.name, t.age);
  11. }
  12. int main()
  13. {
  14. turtle myrtle = {"Myrtle", "Leatherback sea turtle", 99};
  15. happy_birthday(myrtle);
  16. printf("%s's age is now %i\n", myrtle.name, myrtle.age);
  17. return 0;
  18. }

但奇怪的事情发生了……

如何更新结构 - 图2

如何更新结构 - 图3试驾

你编译并运行了代码,结果如下。

如何更新结构 - 图4

奇怪的事情发生了。

这段代码创建了一个新的结构,然后把它传给了一个函数,按理说,函数会将结构中某个字段的值递增1,但程序却……。

你知道age字段在happy_birthday()函数中更新了,因为printf()函数显示了递增以后age的值,但奇怪的是,虽然happy_birthday()更新了age,但程序返回main()函数以后,age又变回了原来的值。

如何更新结构 - 图5脑力风暴

代码的行为十分诡异,但你已经掌握了足够多的信息,应该能推测到底发生了什么,是吧?