(person *)


I have a bit of trouble with the line:

I understand the part before the ‘=’ and the malloc(sizeof(Person) part but I don’t understand (Person *)

Can someone explain why this is there (and better even, what it means?


The malloc returns an object of type void * large enough to hold an object of type Person.

(Person *) typecasts the object of type void * to Person *.

To understand what the typecast operator (T *) as in (Person *) really does, try this:

#import <Foundation/Foundation.h>

struct Foo
    long bar;
typedef struct Foo Foo;

int main (int argc, const char * argv[])
    (malloc (sizeof (Foo)))->bar = 7;         // Error
    ((Foo *)malloc (sizeof (Foo)))->bar = 7;  // Okay

    return 0;


Thanks, I already learned about typecasting in an earlier chapter but never saw it with an object so I was a bit confused by the syntax of (Person *) in combination with malloc.


What is typecasting? I on the “heap” chapter…typecasting was never explained in detail. thx


Hi SmallNerdRacher.
I have had trouble getting my head around typecasting too.

Simply put, typecasting is a way to make a variable of one data type behave like another for a single operation. This is done by putting the type of variable you want the actual variable (say an integer) to act like (lets say a double float) inside parentheses in front of the actual variable .[code]// typeCast

#include <stdio.h>

int main(int argc, const char * argv[])
int sum = 17, count = 5;
double floatCast;

floatCast = (double) sum / count;
printf(“Value of floatCast : %f\n”, floatCast);

return 0;

And now that you have forced or typecast the integer variable to act like a float you get:[quote]Value of floatCast is: 3.400000.[/quote]

Type casting can also be when an actor plays a role and from which they can never escape from. Like that poor actor R.Lee Ermey who played that Staff Sergeant Hartman in Full Metal Jacket. But I digress from the focus of this forum.