结构变量的动态分配

Dynamic Allocation of Structure variable

本文关键字:动态分配 变量 结构      更新时间:2023-10-16

下面是我学到的动态内存分配方法,

int *p = new int; 

pointer-variable = new data-type;

然而,在链接列表的另一个程序中,我看到了的结构延迟

struct node
{
int info;
struct node *next;
}

其实例的声明就像

struct node *temp, *s;
temp = new(struct node);

我的意思是,它应该是错误的,因为根据语法,它不应该包括struct,它应该像这个

node *temp, *s;
temp = new node ;

我哪里错了,有人能指引我吗?

这是源代码,请参阅第125&126.

您的问题实际上与动态分配无关。

当你在C++中说struct node { ... };时,它会创建两个类型名称,nodestruct node,它们都指同一类型:

node x;
struct node y;  // x and y are variables of the same type

这种有点奇怪的行为的原因是C++是基于C的。在C中,struct node { ... };只创建一个类型名称struct node。您必须手动使用typedef才能获得不包含struct:的较短名称

typedef struct node { ... } node;  // C

C++希望在不必到处键入struct的情况下更容易创建短类型名称,同时保持与现有C代码的兼容性。

(此外,还有一个名为stat的通用unix函数,它将指针指向一个也称为stat:的结构

int stat(const char *, struct stat *);

这里struct stat明确地指类型,而不是函数。C++必须支持这种语法才能调用stat。)

您的代码是以一种奇怪的C风格编写的(其中到处都包括struct关键字),但new不存在于C中,因此它不可能是真正的C。

node *temp, *s;
temp = new node ;

这是C++中动态内存分配的语法

然而,

struct node *temp, *s;
temp = (node*)malloc(sizeof(struct node));  

这是C中使用的语法在C中,关键字"struct"必须写在结构名称之前。

关键字"new"在C.中不存在

//这样使用代码。。。。。

struct node *temp, *s;
temp = (struct node*) new(struct node);

//因为temp是一个结构节点指针,所以我们需要在赋值之前对其进行类型转换。。