Home Segments Index Top Previous Next

364: Mainline

From the data-type perspective, malloc generates a pointer that is said to be of type void*. Such void* pointers have the property that they can be cast into pointers of any type.

To cast the result of a call to malloc into a form suitable for assignment to a trade object, you preface the call to malloc by a parentheses-enclosed specification of the appropriate pointer data type.

        *-- Converts address into the form required for  
        |   assignment to trade pointers 
        | 
        |               *-- Produces address of memory  
        |               |   chunk reserved for a trade 
        v               v 
       --------------- ------------------------------ 
tptr = (struct trade*) malloc (sizeof (struct trade)); 

Note that the specification of the data type includes an asterisk—the data type is to be a pointer to a trade object, rather than a trade object.

Also, remember that malloc-containing statements require the C compiler to create executable code that allocates memory for a trade object at run time, rather than at compile time.