为什么malloc返回Void Pointer?/ [英] Why malloc return Void Pointer?/

查看:178
本文介绍了为什么malloc返回Void Pointer?/的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么malloc返回void指针?

因为我们可以将任何数据类型强制转换为任何其他数据类型,那么如果malloc返回int类型指针,那么我们也可以将它转换为另一个数据类型指针,那么为什么返回void指针?

Why malloc return void pointer?
Because we can typecast any data-type into any another data type,then if malloc return int type pointer then also we can typecast it into another data type pointer,then why return void pointer?

推荐答案

原因是malloc对你实际分配的数据类型一无所知;它只是分配原始内存。返回void *可以保证将指针强制转换为有用的东西。返回任何其他指针类型可能会导致您忘记将指针强制转换为它指向的内容。



Btw: int 对于返回值来说是一个非常糟糕的选择,因为它甚至不是指针。不能保证指针值适合 int (例如在许多64位体系结构中都是如此)。处理 int 和指针基本相同是许多C初学者犯的常见错误。一些遗留代码也显示了这个坏习惯。
The reason is that malloc has no clue as to what data type you are really allocating; it just allocates raw memory. Returning a void* guarantees that you cast the pointer to something useful. Returning any other pointer type would risk that you forget to cast the pointer to what it really points to.

Btw: int would be a very bad choice for the return value as it isn''t even a pointer. It is not guaranteed that a pointer value will fit into an int (for example that is so on many 64-bit architectures). Treating an int and a pointer as basically the same is a common error that many C beginners make. And some legacy code also shows this bad habit.


有两个原因,首先,malloc不知道你为什么需要内存。所以它只返回要求返回的字节数。其次(我不确定这是出于这个目的而故意做的)你不能轻易取消引用*因此它可以帮助你避免意外。
There are two reasons, first, malloc doesn''t know why you need memory. So it just return number of bytes asked to return. Secondly (I am not sure this is purposefully done for this reason) you cannot dereference void * easily so it can help you to avoid accidents.


这篇关于为什么malloc返回Void Pointer?/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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