I have a book that says the following:
The malloc() allocation still has one slight problem. We still have to explain the left portion of the temperature malloc(). What is the (int *) for?
The (int *) is a typecast. You’ve seen other kinds of typecasts in this book. To convert a float >value to an int, you place (int) before the floating-point value, like this:
aVal = (int)salary;
The * inside a typecast means that the typecast is a pointer typecast. malloc() always returns a character pointer. If you want to use malloc() to allocate integers, floating points, or any kind of data other than char, you have to typecast the malloc() so that the pointer variable that receives the allocation (such as temps) receives the correct pointer data type. temps is an integer pointer; you should not assign temps to malloc()’s allocated memory unless you typecast malloc() into an integer pointer. Therefore, the left side of the previous malloc() simply tells malloc() that an integer pointer, not the default character pointer, will point to the first of the allocated values.
temps:
int * temps; /* Will point to the first heap value */
temps = (int *) malloc(10 * sizeof(int)); /* Yikes! */
After reading similar threads, it's said that malloc()
returns a pointer of type void, not of type character. Am I missing something? I'm aware that it's not needed to typecast malloc()
in C.