由Malloc分配的结构,为什么?C 代码分析
Struct allocated with malloc, why? C++ code analysis
行:
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 。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 我的字符计数代码计算错误.为什么
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么我的代码在输出中增加了93天
- 为什么在这个代码结束循环中没有得到结束
- 为什么示例代码访问IUnknown中已删除的内存
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么模数运算符不适用于该代码
- 为什么catch中的代码没有被执行
- 这是什么代码?为什么它有效?C++
- 我遇到了一些C++代码.为什么我们必须在块中使用 *this 而不是这个
- 谁能解释这个代码?为什么显示 1
- 超级基本代码:为什么我的循环没有中断
- 琐碎的C++代码..为什么要编译
- 你能告诉我这个代码为什么崩溃吗
- 有人建议我的代码为什么在basic_ios和sstream中创建错误
- 我读取了一个char类型的变量,然后打印出ascii代码.为什么如果我按回车键,什么都没有
- 我为课堂编写了这个汉明编码代码.为什么这么慢