我应该显式转换 malloc() 的返回值吗? [英] Should I explicitly cast malloc()'s return value?
问题描述
我想咨询以下案例:
char *temp;
temp = malloc(10);
由于malloc
的返回类型是void*
,malloc
返回的指针是否会隐式转换为char*
类型在被分配给临时之前?标准在这方面是怎么说的?
Since the return type of malloc
is void*
, will the pointer returned by the malloc
be implicitly cast to char*
type before being assigned to temp? What does the standard say in this regard?
如果我们的指针变量是某种结构类型,例如:
If our pointer variable is some struct type for example:
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
如果我们将内存分配给 temp 而不将其转换为 struct node*
类型,它会被隐式转换为 struct node*
类型还是有必要显式转换它struct node*
类型?
If we allocate memory to temp without casting it to struct node*
type, will it be implicitly cast to struct node*
type or is it necessary to explicitly cast it to struct node*
type?
推荐答案
C 中的空指针可以分配给任何指针,无需显式转换.
A void pointer in C can be assigned to any pointer without an explicit cast.
这篇关于我应该显式转换 malloc() 的返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!