當將一個結構體傳遞給另一個函數時,通常會更好地按照上面的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
結構的實例 - student *s
。在main()
,我們創建student
結構的實例,然後使用引用操作符(&
)傳遞給它的引用,我們addStudent()
功能。
在addStudent()
函數中,我們可以使用箭頭運算符(->
)來取消引用指針,並訪問它的任何成員(功能上相當於:(*s).age
)。
當我們返回main()
時,我們在addStudent()
函數中所做的任何更改都會反映出來,因爲指針爲我們提供了內存中student
結構實例存儲位置的引用。這由printf()
來說明,在這個例子中它將輸出「10」。
如果你沒有通過引用,你實際上會使用你傳遞給函數的結構體的副本,這意味着當你返回到main
時,任何改變都不會被反映 - 除非你實現了一種傳遞方式結構的新版本返回到主或沿着這些行的東西!
雖然指針看起來倒胃口首先,一旦你得到你的頭圍繞它們是如何工作以及爲什麼它們是那麼得心應手,他們成爲第二天性,你想知道你曾經沒有他們應對!
你在哪裏聲明你的結構?在你的實際實現文件中,你的'struct student {/ * ... * /};'代碼在哪裏?它看起來像它在錯誤的範圍(如在'main'功能或任何函數中聲明你想從調用'addStudent' ... – 2012-04-29 06:04:28
是的它在我的功能範圍 – 2012-04-29 06:06:50