Why casting (Person *)


Why should we cast (Person *) onto malloc(sizeof(person));
I know that person is a type but why cast it onto a memory?


The [b]malloc/b function returns a pointer to a bunch of bytes. That’s all. We’ve requested enough bytes to store a Person struct, but [b]malloc/b doesn’t care. It’s all just a pile of bytes to [b]malloc/b. So once we’ve requested enough bytes for a Person struct, if we want to actually treat those bytes like a Person struct, we need to cast the pointer that malloc() gave us (which is void pointer) to a Person pointer. Otherwise, if I try so say: myPerson->height = 2.2; but the compiler doesn’t know that the memory that the myPerson variable points to is supposed to be a Person struct, then the compiler will complain.


Your answer makes sense, however when I removed the cast (Person *) the program can still compile and run doing so.

instead of

Wouldn’t the compiler know it belongs to the Person struct since the pointer takes on the type of Person *? So type casting Person * on the malloc is kind of excessive?

It be equivalent of doing

Where doing (int) is not necessary?


sizeof(Person) returns the total size of all the var types within Person, but doesn’t tell malloc how to allocate those bytes. By casting the block of memory malloc returns into the type Person we are effectively formatting the chunk of memory into the various components.

You don’t need to cast int because the block of memory set aside to hold the int primitive is already structured in the sytem.

Mark H


I’m sorry, you’re right. The analogy doesn’t work because b[/b] is implicitly already an int and is being stored into an int, whereas the return from malloc() is declared as void* but being stored into a Person*, but the overall point is correct: there is no actual need to cast the return value from malloc() here.

The next printing of the book will drop the cast. Good catch!