为什么当我没有转换malloc的结果时编译器会抱怨? [英] Why does the compiler complain when I do not cast the result of malloc?

查看:129
本文介绍了为什么当我没有转换malloc的结果时编译器会抱怨?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查不需要显式转换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


推荐答案

的C编译器。因为C ++需要显式转换。
问题不是(un)强制转换 malloc 结果,而是指向其他指针的任何void指针。

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.

这篇关于为什么当我没有转换malloc的结果时编译器会抱怨?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆