为什么《C 程序设计语言》书上说我必须投malloc? [英] Why does "The C Programming Language" book say I must cast malloc?

查看:23
本文介绍了为什么《C 程序设计语言》书上说我必须投malloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我到达了 167 页>The C Programming Language(第二版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 如果请求无法得到满足.存储被初始化为零.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*有很好的解释为什么不强制转换 malloc.

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 辩护,我向丹尼斯·里奇征求意见,我可以引用上面从第 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 规则.

这篇关于为什么《C 程序设计语言》书上说我必须投malloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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