c++ - 结构体用malloc分配,为什么? C++代码分析

标签 c++ c list struct

行:

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

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

另外,struct的重新声明是多余的吗?

下面的代码不能完成同样的任务吗?

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;
}  

最佳答案

你问了

Wouldn't Node* newNode = new Node; accomplish the same task?

不,这在某些非常重要的方面并不等同。如果此函数的接口(interface)(契约)的一部分是它返回一个可以传递给 free() 的指针,那么使用 new 实现它就会违反该契约。

此外,重复冗余地使用 struct 关键字表明我们已尽力确保此代码能够正确编译为纯 C 和 C++。

关于c++ - 结构体用malloc分配,为什么? C++代码分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22336904/

相关文章:

c - 错误[e46] : Undefined external "set_all_ports" referred in GPIO main

c - 无法将字符串添加到 C 中的 LinkedList

C# 为什么当我清除原始对象时我的列表项被清空?

python - 不懂python pop altering multiple variables

python - 如何在迭代文件路径字符串列表时获取索引和文件名?

c++ - C++ 的 Rails 迁移

从应用程序传递给 qemu 的 CPU 写入值很奇怪

c++ - 为什么我会收到错误 C1033 : cannot open program database in VS 2010

c++ - 未找到 Windows7 pthread.h

c++ - 将 C++ 的相同功能/概念转换为序言