Having some trouble with allocating memory pg. 70


Hi everyone! I was wondering if someone would be able to explain to me the line of code on page 70 where the memory is allocated for the one Person structure.

Here is the code:

//Allocate memory for one Person Structure Person *x = (Person *)malloc(sizeof(Person));

I’m particularly confused about the (Person *) bit.



That bit is called typecasting.

Person * means a pointer, a pointer to a Person object which happens to be a plain struct.

Note that we can’t do this:

Person x = (Person *)malloc (sizeof (Person));

because malloc () returns an address which can only be assigned to a variable of pointer type.

That’s why we need to do something like this:

Person * x = malloc (sizeof (Person));

But malloc is declared as:

void * malloc (size_t size);

Its return type is void*, which means address of anything.

That’s why we need to typecast the value returned by malloc (): from void* to Person *:

Person * x = (Person *)malloc (sizeof (Person));

Hence the (Person *) typecasting.


Thanks! This really clears things up. :smiley:


I second that! This explanation about the typecast and that explanation http://forums.bignerdranch.com/viewtopic.php?f=143&t=4356 about the -> operator really would have been necessary in Chapter 11. Seems to me like Aaron was in a hurry there to get to Part III of the book :wink:.