[英]Struct pointer in struct
我無法理解結構中的結構指針。 你能試着向我解釋一下,或者推薦一些有趣的讀物來解釋這個概念嗎? 我不知道這是不是一個太籠統的問題,在這種情況下,我很抱歉。
例子:
struct person{
struct person* mother;
struct person* father;
int birthday;
};
struct person john;
struct person alice;
struct person rachael;
john.birthday = 1988;
alice.mother = &rachael;
alice.mother->birthday = 1970;
根據您的評論,這部分:
alice.mother->birthday = 1970;
相當於這個:
(*(alice.mother)).birthday = 1970;
alice.mother
的類型為struct person*
(*(alice.mother))
取消引用指針,所以類型是struct person
(*(alice.mother)).birthday
讓你可以訪問struct person
的生日字段,所以現在你可以給它賦值。
C 只是以->
的形式提供語法糖,這樣您就不必編寫替代方案,這是一個丑陋的爛攤子
所以你有一個結構,它具有指向同一種結構的指針引用,這在 C 中是合法的,而包括整個結構(以及元素的 memory)將不起作用,因為它是遞歸的......
struct person{
int age; // sizeof(int) bytes
person mom; // sizeof(int) + sizeof person, which is sizeof int bytes + sizeof person...
};
那是行不通的,因為它需要無限的 memory 來存儲。
所以你必須存儲一個指向實例的指針,它是一個存儲實例地址的變量,或者 NULL (在一個表現良好的程序中,它可能不應該是任何其他值)
struct person{
int age; // sizeof(int) bytes
person * mom; // sizeof (*person)...
};
所以現在我們可以開始做事了
person QueenMother; // these have storage, but are garbage data
person QueenElizabethII;
這兩個都在堆棧上,他們使用的所有 memory 都在那里使用。 正如您所指出的,您可以進行分配:
QueenElizabethII.mom = &QueenMother;
所以指向媽媽的指針是 QueenMother 的地址......這有效,現在如果你想通過 QueenElizabethII 實例設置 QueenMother 的年齡,你可以。
(*QueenElizabethII.mom).age = 102; // dereference and dot accessor.
//which you could also write as
QueenElizabethII.mom->age = 102; // pointer to member accessor
現在,如果我們想動態地重寫這一切,我們可以這樣做:
struct person{
int age; // sizeof(int) bytes
person * mom; // sizeof(int) + sizeof (*person)...
};
person * QueenMother; // these dont have storage yet;
person * QueenElizabethII;
QueenElizabethII = malloc(sizeof(person)); // now we have storage, but the data is garbage... we can initialize it to 0 with memset, or bzero; or you can do this:
QueenMother = calloc(1,sizeof(person)); // calloc is like malloc, but it zero's the data in the return
QueenElizabethII->mother = QueenMother; // now this syntax is smoother
QueenElizabethII->age = 94;
QueenElizabethII->mother->age=102; // if you are so inclined.
使用此策略時您始終需要注意的一件事是,您需要檢查指針是否實際指向某個地方,否則您將崩潰...
if(QueenElizabethII->mother){
QueenElizabethII->mother->age=102; // now that is safe... probably
}
當你完成 memory 后,我應該補充一點,你應該釋放它:
free(QueenElizabethII);
free(QueenMother);
否則你有泄漏
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.