行:
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/