gpt4 book ai didi

c - 为什么 malloc 返回的指针在使用前不需要转换,与其他 (void *) 指针不同

转载 作者:行者123 更新时间:2023-11-30 18:25:55 24 4
gpt4 key购买 nike

编译器(这里我正在考虑 gcc,但我猜它可能是任何 C 编译器)是否关心变量来自哪里?如果指针来自 malloc,为什么会有所不同?它只是某些编译器使用的优化还是 C 标准中提到的?

最佳答案

unlike other (void *) pointers

实际上,在 C 中,没有 void * 需要强制转换,malloc 在这方面没有什么特别之处。只要您处理的是对象指针(即不是函数指针),您就可以自动在 void * 之间进行转换。

or is it mentioned in the C standard

<小时/>

我们什么时候需要显式强制转换?标准是这样说的:

6.5.4 Cast Operators

Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast.

转发到该部分:

[...]one operand is a pointer to an object type, and the other is a pointer to a qualified or unqualified version of void [...]

所以你已经得到它了。 void * 不需要显式转换。

关于c - 为什么 malloc 返回的指针在使用前不需要转换,与其他 (void *) 指针不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com