C语言: pointer returned by malloc() and casting

标签 c pointers memory malloc

Possible Duplicate:
Do I cast the result of malloc?
What is the Best Practice for malloc?

我是 C 语言新手,我有一个问题 正如我在类里面所解释的:

The type of the pointer returned by malloc() is void *, and therefore we need to cast it into the required type

这意味着我需要做:

char *str;
str = (char *) malloc(14);

但是我不明白,这是必须的吗?假设 malloc 返回 void 指针,为什么我看到许多关于而不进行转换的示例?一个例子:

float *arr = malloc (20 * sizeof (float));

有人可以解释一下吗:)?

最佳答案

在 C 中,不需要进行此强制转换。转换确实是隐式的。

C11 (n1570), § 6.3.2.3 Pointers

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

由于它是不必要的,因此是否强制转换 malloc 返回是另一个问题(请参阅 here )。

关于C语言: pointer returned by malloc() and casting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14414854/

相关文章:

c - strcpy 和 memcpy 之间的重叠

c - 为什么如果条件以一种奇怪的方式工作

c++ - 如何将 C++ 引用传递给 C 函数的指针参数?

java - 设置jre环境参数时,是使用java控制面板系统选项卡还是用户选项卡

c - 如何向 float 手动输入 IEEE 754?

c++ - 尝试在 C++ 中删除具有空地址(非 NULL)的数组指针

c - 无法使指向数组的指针正常工作 - 应用程序崩溃

c++ - 写入指定内存位置

c - 我是否必须在 C 中使用 malloc() 分配的内存上调用 free() ?

c - 使用 malloc 创建指向指针的指针数组时出现段错误