为什么 calloc 有两个参数,而 malloc 只有一个?
IMO 一个就足够了,为什么 calloc
需要将其分成两个参数?
IMO one is enough, why does calloc
require to split it into two arguments?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜这可能是历史,并且早于 C 拥有函数原型的时代。在没有原型的情况下,参数基本上必须是 int,typedef 可能还没有发明。但是,
INTMAX
是您可以使用malloc
分配的最大块,将其分成两部分只会给您带来更大的灵活性,并允许您分配非常大的数组。即使在那个时候,也有一些方法可以从系统中获取默认归零的大页面,因此对于calloc
而言,效率问题并不比对于malloc
而言更大。如今,有了
size_t
和手头的函数原型,这只是每天提醒我们丰富的 C 历史。I'd guess that this is probably history and predates the times where C had prototypes for functions. At these times without a prototype the arguments basically had to be
int
, thetypedef
size_t
probably wasn't even yet invented. But thenINTMAX
is the largest chunk you could allocate withmalloc
and splitting it up in two just gives you more flexibility and allows you to allocate really large arrays. Even at that times there were methods to obtain large pages from the system that where zeroed out by default, so efficiency was not so much a problem withcalloc
than formalloc
.Nowadays, with
size_t
and the function prototype at hand, this is just a daily reminder of the rich history of C.参数名称很好地说明了这一点:
后一种形式允许通过提供元素数量和元素大小来整齐地分配数组。使用
malloc
通过乘法可以实现相同的行为。但是,
calloc
还将分配的内存初始化为 0。malloc
不进行 init,因此该值未定义。理论上,由于没有设置所有内存,malloc
可以更快;只有大量的情况下才可能注意到这一点。在这个问题中,建议
calloc
是clear-alloc,malloc
是mem-alloc。The parameter names document it reasonably well:
The latter form allows for neat allocating of arrays, by providing the number of elements and element size. The same behavior can be achieved with
malloc
, by multiplying.However,
calloc
also initializes the allocated memory to 0.malloc
does no init, so the value is undefined.malloc
can be faster, in theory, due to not setting all the memory; this is only likely to be noted with large amounts.In this question, it is suggested that
calloc
is clear-alloc andmalloc
is mem-alloc.