Reputation: 249
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.
Upvotes: 5
Views: 129
Reputation: 134286
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
.
Upvotes: 5
Reputation: 5011
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.
Upvotes: 1