Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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. 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.

like image 300
LA Hattersley Avatar asked Apr 22 '16 08:04

LA Hattersley


2 Answers

I understand that struct Person returns a pointer (*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. This is not a definition of 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.

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

like image 121
Sourav Ghosh Avatar answered Sep 30 '22 02:09

Sourav Ghosh


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

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

like image 21
Marievi Avatar answered Sep 30 '22 02:09

Marievi