将结构传递给另一个函数时,通常最好按照 Donnell 上面的建议进行,而是通过引用传递它。
这样做的一个很好的理由是,如果您想要进行更改,这些更改将在您返回到创建它的实例的函数时反映出来,这会使事情变得更容易。
这是执行此操作的最简单方法的示例:
#include <stdio.h>
typedef struct student {
int age;
} student;
void addStudent(student *s) {
/* Here we can use the arrow operator (->) to dereference
the pointer and access any of it's members: */
s->age = 10;
}
int main(void) {
student aStudent = {0}; /* create an instance of the student struct */
addStudent(&aStudent); /* pass a pointer to the instance */
printf("%d", aStudent.age);
return 0;
}
在此示例中,addStudent()
函数的参数是指向student
struct -实例的指针student *s
。在main()
中,我们创建结构的一个实例,然后使用引用运算符 ( ) 将对student
它的引用传递给我们的函数。addStudent()
&
在addStudent()
函数中,我们可以使用箭头运算符 ( ->
) 来取消引用指针,并访问它的任何成员(功能上等同于: (*s).age
)。
我们在addStudent()
函数中所做的任何更改都会在我们返回时反映出来main()
,因为指针为我们提供了对内存中存储结构实例的位置的引用student
。这由 来说明,printf()
在本例中将输出“10”。
如果您没有传递引用,您实际上将使用您传递给函数的结构的副本,这意味着当您返回时不会反映任何更改main
- 除非您实现了一种传递新版本的方法结构回到主线或类似的东西!
虽然指针起初可能看起来令人反感,但一旦你了解它们的工作原理以及它们为何如此方便,它们就会成为第二天性,你会想知道没有它们你是如何应对的!