由Malloc分配的结构,为什么?C 代码分析

Struct allocated with malloc, why? C++ code analysis

本文关键字:代码 为什么 Malloc 分配 结构      更新时间:2023-10-16

行:

struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

为什么要实例化的新结构涉及malloc(为结构的大小分配内存块)?

另外,结构冗余的重新陈述是重新陈述吗?

以下任务无法完成相同的任务?

Node* newNode = new Node; 

模式代码下面:

#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};
struct List
{
    struct Node *head;  // pointer to head node of list
};
//creates a new list Node
struct Node* newListNode(int data)
{
    struct Node* newNode =
            (struct Node*) malloc(sizeof(struct Node));
    newNode->dest = dest;
    newNode->next = NULL;
    return newNode;
}  

您问

Node* newNode = new Node;不能完成相同的任务吗?

不,这在某些非常重要的方式上并不等于。如果此功能的接口(合同)的一部分是它返回可以将可以传递给free()的指针,然后使用new实施它会违反该合同。

此外,重复使用struct关键字的冗余使用表明,已经努力确保该代码正确地编译为普通C和C 。