为什么"The C Programming Language"书说我必须投malloc吗? [英] Why does "The C Programming Language" book say I must cast malloc?

查看:73
本文介绍了为什么"The C Programming Language"书说我必须投malloc吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我到达了167 > C编程语言(第二版Brian W. Kernighan和Dennis M. Ritchie),发现作者说我必须转换malloc.这是本书的一部分:

Today I reached page 167 of The C Programming Language (second edition Brian W. Kernighan & Dennis M. Ritchie) and found that the author says I must cast malloc. Here is the part from the book:

7.8.5存储管理

malloc和calloc函数动态获取内存块.

The functions malloc and calloc obtain blocks of memory dynamically.

void *malloc(size_t n)

返回一个指向n字节未初始化存储的指针,如果无法满足请求,则返回NULL.

returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied.

void *calloc(size_t n, size_t size)

将指针返回给具有指定大小的n个对象的数组的足够的可用空间;如果为null,则返回NULL 该请求无法满足.存储器初始化为零. malloc或calloc返回的指针与所讨论的对象具有正确的对齐方式, 但必须将其转换为适当的类型,如

returns a pointer to enough free space for an array of n objects of the specified size, or NULL if the request cannot be satisfied. The storage is initialized to zero. The pointer returned by malloc or calloc has the proper alignment for the object in question, but it must be cast into the appropriate type, as in

int *ip;
ip = (int *) calloc(n, sizeof(int));

我已经知道malloc(及其家族)返回的类型为 void *

I already know that malloc (and its family) returns type void*, and there are good explanations why not to cast malloc.

但是我的问题是:为什么这本书说我应该抛弃它?

But my question is: Why does the book say I should cast it?

推荐答案

来自 http://computer-programming-forum.com/47-c-language/a9c4a586c7dcd3fe.htm :

在ANSI C之前的版本中-如K& R-1中所述-malloc()返回了char * 并且有必要在所有情况下都将其返回值转换为 接收变量也不是char *.输入新的void * 标准C使得这些扭曲是不必要的.

In pre-ANSI C -- as described in K&R-1 -- malloc() returned a char * and it was necessary to cast its return value in all cases where the receiving variable was not also a char *. The new void * type in Standard C makes these contortions unnecessary.

使任何人免于不必要的跨越而陷入尴尬的困境 为K& R-2辩护,我请丹尼斯·里奇(Dennis Ritchie)提出我可以 引用上文第142页中引用的句子的有效性.他 回答:

To save anybody from the embarrassment of leaping needlessly to the defence of K&R-2, I asked Dennis Ritchie for an opinion that I could quote on the validity of the sentence cited above from page 142. He replied:

无论如何,现在我重新阅读了p上的内容. 142,我认为是 错误的;它的编写方式不仅具有防御性 违反早期的规则,就歪曲了ANSI规则.

In any case, now that I reread the stuff on p. 142, I think it's wrong; it's written in such a way that it's not just defensive against earlier rules, it misrepresents the ANSI rules.

这篇关于为什么"The C Programming Language"书说我必须投malloc吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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