[英]Why is there a nested pointer inside a C struct definition?
I'm working through Learn C The Hard Way and am struggling to understand something in Exercise 16: Structs And Pointers To Them. 我正在通过学习C The Hard Way来努力,并且正在努力去理解练习16中的内容:结构和指针。
struct Person *Person_create(char *name, int age, int height, int weight)
{
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
I understand that struct Person returns a pointer (*person_create) to the start of the struct. 我理解struct Person将一个指针(* person_create)返回到struct的开头。 But why is there a second struct definition to Person immediately nested inside?
但是为什么有人第二个结构定义立即嵌套在里面? Pointing to *who?
指着谁?
Can somebody shed some light on this for me. 有人可以为我阐明这一点。 Or point me towards a better explanation of struct definitions in C.
或者指出我在C中更好地解释结构定义。
I understand that
struct Person
returns a pointer (*person_create
)我理解
struct Person
返回一个指针(*person_create
)
Wait, it's not what you think, or at least you don't say it that way.... 等等,这不是你的想法,或者至少你不这么说......
Here, person_create()
is a function , which returns a pointer to struct Person
. 这里,
person_create()
是一个函数 ,它返回一个指向struct Person
的指针。 This is not a definition of struct Person
. 这不是
struct Person
的定义。
Now, that said, coming to your actual quetion, struct Person *who
does not define the struct Person
, rather, it defines a variable who
which is a pointer to struct Person
. 现在,就是说,进入你的实际排队,
struct Person *who
没有定义struct Person
,而是定义了一个变量who
它是一个指向struct Person
的指针。
For ease of understanding, consider int someRandomVariable = 0
. 为了便于理解,请考虑
int someRandomVariable = 0
。 It does not define int
, right? 它没有定义
int
,对吗? It defines a variable someRandomVariable
of type int
. 它定义了一个
int
类型的变量someRandomVariable
。
The function returns a pointer of type struct Person *
, in other words a pointer to a struct Person
. 该函数返回
struct Person *
类型的指针,换句话说,指向struct Person
的指针。
In particular here the pointer you will return is named who
, as you can understand from the declaration struct Person * who = ...
. 特别是在这里,你将返回的指针被命名为
who
,你可以从声明struct Person * who = ...
理解。 Therefore, you need to allocate memory for the variable who
, which you will fill, and return a pointer to. 因此,你需要为变量分配内存
who
,你将填补,并返回一个指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.