C语言 C 中的 Malloc 语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15553602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Malloc syntax in C
提问by Shy Student
In the books I read that the syntax for malloc is malloc(sizeof(int)) but in one of doubly linked list program I see the following:
在我读过的书中,malloc 的语法是 malloc(sizeof(int)) 但在双向链表程序之一中,我看到以下内容:
newnode=(struct node *)malloc(sizeof(struct node))
What is (struct node*) doing here? What is this entire code doing? btw, the code for the struct in the program is as below.
(struct node*) 在这里做什么?整个代码在做什么?btw,程序中结构体的代码如下。
struct node
{
char line[80];
struct node *next,*prev;
};
struct node *start=NULL,*temp,*temp1,*temp2,*newnode;
Thank you
谢谢
回答by Inisheer
The code is dynamically creating a pointerto a single type of struct node. In most versions of C, the (struct node *)cast is not needed, and some argue that it shouldn't be used. If you remove the cast, it will be a void*, which can be used for any type.
该代码正在动态地创建pointer单一类型的struct node. 在大多数版本的 C 中,(struct node *)不需要强制转换,有些人认为不应该使用它。如果删除演员表,它将是 a void*,可用于任何类型。
Therefore:
所以:
newnode = (struct node*)malloc(sizeof(struct node));
is roughly equivalent to:
大致相当于:
newnode = malloc(sizeof(struct node));
See: Specifically, what's dangerous about casting the result of malloc?
请参阅:具体来说,强制转换 malloc 的结果有什么危险?
Note 1: If you are using Visual Studio to write your C code, it will give you red underlining if you don't cast the result of malloc. However, the code will still compile.
注意 1:如果您使用 Visual Studio 编写 C 代码,如果您不将malloc. 但是,代码仍将编译。
Note 2: Using mallocin C++ code requires you to cast the result as shown in your example.
注 2:malloc在 C++ 代码中使用需要您按示例中所示强制转换结果。
回答by Shy Student
You ran into a very bad code. C programmers never cast a result of malloc(). Not only it is not needed but can be harmful.
你遇到了一个非常糟糕的代码。C 程序员从不强制转换malloc(). 它不仅不需要,而且可能有害。
回答by Pradheep
malloc returns a void pointer .
malloc 返回一个空指针。
(struct node*) does a explicit conversion from void pointer to the target pointer type
(struct node*) 执行从 void 指针到目标指针类型的显式转换
回答by Ivaylo Strandjev
You should pass the number of bytes that you want mallocto allocate as argument. That is why in this code sample you use sizeof(struct node)telling Cto allocate the number of bytes needed for a struct node variable. Casting the result like is shown in this code is bad idea by the way.
您应该将要malloc分配的字节数作为参数传递。这就是为什么在此代码示例中,您使用sizeof(struct node)tellC来分配结构节点变量所需的字节数。顺便说一下,像这段代码中显示的那样投射结果是个坏主意。
回答by Brad
"malloc" returns a void-pointer. (struct node *) is type-casting the result of malloc to a "node struct pointer", which is (undoubtibly) what "newnode" is.
“malloc”返回一个空指针。(struct node *) 将 malloc 的结果类型转换为“节点结构指针”,这(毫无疑问)是“newnode”。

