[英]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.