简体   繁体   中英

Why does the compiler complain when I do not cast the result of malloc?

I am inspecting code that does not require explicitly casting result of malloc call but whenever I attempt to do this, the compiler throws an error.

ie

char *somevar;
somevar = malloc(sizeof(char) * n); //error
somevar = (char *)malloc(sizeof(char) * n); // ok

This happens if you use C++ compiler instead of C compiler. As C++ requires explicit casting. The problem is not just with (un)casting malloc result, but any void pointer to other pointer.

Did you remember to include the function prototype? For malloc(3), this is:

#include <stdlib.h>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM