Why is there a nested pointer in the definition of structure C?

I'm working on Learn C The Hard Way and struggling to figure something out in Exercise 16: Structures and pointers to them.

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 beginning of the structure. But why is there a second definition of structure for a Person immediately nested inside? Pointing to whom?

Can someone shed some light on this for me. Or give me a better explanation of the structure descriptions in C.

+5
source share
2 answers

I understand that struct Person returns a pointer ( *person_create )

Wait, that’s not what you think, or at least you don’t say so.

Here person_create() is a function that returns a pointer to a struct Person . This is not a definition of struct Person .

Now, leading to your action, struct Person *who does not define a struct Person , rather, it defines a who variable, which is a pointer to a struct Person .

For convenience, consider int someRandomVariable = 0 . It does not define int , right? It defines a variable someRandomVariable type int .

+5
source

The function returns a pointer of type struct Person * , in other words, a pointer to a struct Person .

In particular, the pointer you will return is called who , as you can understand from the declaration struct Person * who = ... Therefore, you need to allocate memory for the who variable that you fill in and return a pointer to.

+1
source

Source: https://habr.com/ru/post/1247691/


All Articles