0

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?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.