The Function malloc is most commonly used to attempt to ``grab'' a portion of memory (There are others - Appendix ). It is defined by:
char *malloc(int number_of_bytes)
That is to say it returns a pointer to a character that is the start in memory of the reserved portion of size number_of_bytes. If memory cannot be allocated a NULL pointer is returned.
attempts to get 100 bytes and assigns the start address to cp.
If you want a pointer to another data type you must use coercion. Also it is usual to use the sizeof() function to specify the number of bytes:
The (int *) means coercion to an integer pointer. Coercion to the correct pointer type is very important to ensure pointer arithmetic is performed correctly.
It is good practice to use sizeof() even if you know the actual size you want - it makes for device independent (portable) code.
sizeof can be used to find the size of any data type, variable or structure. Simply supply one of these as an argument to the function.
In the above we can use the link between pointers and arrays to treat the reserved memory like an array. i.e we can do things like:
ip = 100;