josh_balmer
josh_balmer

Reputation: 43

Struct keyword inside a struct declaration

This is from the following webpage: http://c.learncodethehardway.org/book/ex16.html

....deleted code

struct Person {
    char *name;
    int age;
    int height;
    int weight;
};

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;
}

[Rest of code not shown]

I am not able to understand the statement "struct Person *who = malloc(sizeof(struct Person));

This statement is inside struct Person *Person_create function. So what exactly is struct Person *who doing?

Upvotes: 0

Views: 69

Answers (3)

Piyush Vishwakarma
Piyush Vishwakarma

Reputation: 36

'who' is just a temporary pointer of type struct person that is pointed to the block of memory. So malloc(sizeof(struct Person) creates that block and assigns its address to 'who'. Now to access every element within this block, who->name will be a pointer the name element of that block,and so on. The pointer 'who' is returned at the end for any further operations of the same block.

Upvotes: 1

eric_the_animal
eric_the_animal

Reputation: 432

malloc(sizeof(struct Person)) is allocating a memory block based on the size of struct 'Person' and returns a pointer to the beginning of the new memory block to *who.

Upvotes: 0

midor
midor

Reputation: 5557

Unlike in other languages, it is necessary to prefix a struct with the struct keyword every time unless you typedef the struct. Therefore struct Person *who is simply the declaration of a pointer with the name who to a struct Person.

Upvotes: 0

Related Questions