[英]Brackets containing a datatype on right hand side of assignment operator
I'm trying to understand why I sometimes see brackets containing a data type on the right hand side of an assignment operator in C.我试图理解为什么我有时会在 C 中的赋值运算符的右侧看到包含数据类型的括号。
Specifically I was trying to implement a linked list and because I'm still new to CI was using this to guide me.具体来说,我试图实现一个链表,因为我还是 CI 的新手,所以我用它来指导我。
I came across this line: struct node* link = (struct node*) malloc(sizeof(struct node));
我遇到了这一行:
struct node* link = (struct node*) malloc(sizeof(struct node));
It's part of the instertFirst
function which, I guess, adds a new item to the head of the linked list.它是
instertFirst
函数的一部分,我猜它会向链表的头部添加一个新项目。
Breaking this line down according to my current understanding it states: create a struct node
pointer called link
that points to a newly allocated chunk of memory that is the size of the node
struct.根据我目前的理解,将这一行分解为:创建一个名为
link
的struct node
指针,该指针指向一个新分配的内存块,该内存块是node
结构的大小。
What exactly then is the purpose of (struct node*)
?那么
(struct node*)
的目的究竟是什么? My best guess is that it gives that newly allocated chunk of memory a type...?我最好的猜测是它为新分配的内存块提供了一种类型......?
The function malloc
returns a pointer of the type void *
independent on for which object the memory is allocated.函数
malloc
返回一个类型为void *
的指针,与分配内存的对象无关。
In C a pointer of the type void *
may be assigned to a pointer of any other object type.在 C 中,
void *
类型的指针可以分配给任何其他对象类型的指针。
So you could write所以你可以写
struct node* link = malloc(sizeof(struct node));
In C++ such an implicit conversion is prohibited.在 C++ 中,这种隐式转换是被禁止的。 You need explicitly to cast the returned pointer of the type
void *
to the type struct node *
like您需要明确地将类型为
void *
的返回指针void *
转换为类型struct node *
就像
struct node* link = (struct node*) malloc(sizeof(struct node));
In C as it was mentioned above such a casting is redundant and sometimes only used for self-documenting of the code.在上面提到的 C 中,这样的转换是多余的,有时仅用于代码的自我记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.