Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does malloc() always return a character pointer?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

As user207421 mentioned in the comments, your book is most likely pretty old. Originally, C didn’t have a generic pointer type (i.e., void*). I forget when this was added. The closest thing back then was char* since every pointer, no matter its type, can be safely cast to and from a char* (sort of).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading