malloc 中是否需要类型转换?
malloc 中类型转换有什么用?如果我不在 malloc 中编写类型转换,那么它会返回什么? (为什么 malloc 中需要类型转换?)
What is the use of typecast in malloc? If I don't write the typecast in malloc then what will it return? (Why is typecasting required in malloc?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我假设你的意思是这样的:
int *iptr = (int*)malloc(/* Something */);
在 C 中,你不必(也不应该)强制转换返回指针来自
malloc
。它是一个void *
,在 C 中,它被隐式转换为另一种指针类型。int *iptr = malloc(/* Something */);
是首选形式。
这不适用于 C++,它不共享相同的
void *
隐式转换行为。I assume you mean something like this:
int *iptr = (int*)malloc(/* something */);
And in C, you do not have to (and should not) cast the return pointer from
malloc
. It's avoid *
and in C, it is implicitly converted to another pointer type.int *iptr = malloc(/* something */);
Is the preferred form.
This does not apply to C++, which does not share the same
void *
implicit cast behavior.在 C 语言中,您永远不应该强制转换
malloc()
的返回值。这样做是:void *
与任何其他指针类型兼容(函数指针除外,但这并不适用于此)。所以:没有任何好处,至少有三个缺点,因此应该避免。
You should never cast the return value of
malloc()
, in C. Doing so is:void *
is compatible with any other pointer type (except function pointers, but that doesn't apply here).So: there are no benefits, at least three drawbacks, and thus it should be avoided.
您不需要强制转换
malloc
的返回值。 C 常见问题解答中对此进行了进一步讨论:http://c-faq.com/malloc/cast。 html 和 http://c-faq.com/malloc/mallocnocast.html。You're not required to cast the return value of
malloc
. This is discussed further in the C FAQ: http://c-faq.com/malloc/cast.html and http://c-faq.com/malloc/mallocnocast.html .仅仅因为 malloc 返回一个
void
* 并且由于void*
尚未定义大小,因此您无法对其应用指针算数。因此,您通常将指针转换为分配的内存块实际指向的数据类型。Just because malloc returns a
void
* and sincevoid*
has not defined size you can't apply pointer aritmetic on it. So you generally cast the pointer to the data type your allocated memory block actually points.答案是正确的,我只是有一个建议:
The answers are correct, I just have an advice: