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/