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

对着背影说爱祢 提交于 2019-12-30 11:24:06

问题


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.

i.e.

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

回答1:


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.




回答2:


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

#include <stdlib.h>


来源:https://stackoverflow.com/questions/10568301/why-does-the-compiler-complain-when-i-do-not-cast-the-result-of-malloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!