C++ 结构变量的动态分配
下面是我学习的动态内存分配方法C++ 结构变量的动态分配,c++,data-structures,linked-list,structure,C++,Data Structures,Linked List,Structure,下面是我学习的动态内存分配方法 int *p = new int; i、 e 然而,在另一个链表节目中,我看到了结构的变化 struct node { int info; struct node *next; } 其实例的声明如下 struct node *temp, *s; temp = new(struct node); 我的意思是它应该是错误的,因为根据语法,它不应该包括struct,它应该是这样的 node *temp, *s; temp = new no
int *p = new int;
i、 e
然而,在另一个链表节目中,我看到了结构的变化
struct node
{
int info;
struct node *next;
}
其实例的声明如下
struct node *temp, *s;
temp = new(struct node);
我的意思是它应该是错误的,因为根据语法,它不应该包括struct,它应该是这样的
node *temp, *s;
temp = new node ;
我错在哪里了,有人能指引我吗
这是最新版本,请参阅第125和126行的代码
node *temp, *s;
temp = new node ;
这是C语言中动态内存分配的语法++
但是,
struct node *temp, *s;
temp = (node*)malloc(sizeof(struct node));
这是C语言中使用的语法
在C语言中,关键字“struct”必须写在结构名称之前
关键字“new”在C中不存在。你的问题与动态分配无关,真的 当你说结构节点{…};在C++中,它创建了两个类型名称,即节点和结构节点,它们都引用相同的类型:
node x;
struct node y; // x and y are variables of the same type
这种行为有点奇怪的原因是C++基于C中的C,Stult节点{…};仅创建一个类型名称,即struct node。您必须手动使用typedef来获取不包含struct的较短名称:
C++希望更容易地创建短类型名,而不必到处键入struct,同时保持与现有C代码的兼容性 此外,还有一个名为stat的常见unix函数,它使用指向结构(也称为stat)的指针: 这里struct stat明确地指的是类型,而不是函数。C++必须支持这个语法才能调用STAT.<您的代码是以一种奇怪的类似C的风格编写的,其中到处都包含struct关键字,但C中不存在new,因此它不可能是实际的C。//请像这样使用代码
struct node *temp, *s;
temp = (struct node*) new(struct node);
//因为temp是一个结构节点指针,所以我们需要在赋值之前对其进行类型转换在C中,新的不存在。我把它称为C++代码。链接在这里,请参见C@Brijesh的第125&126temp=malloc sizeof*temp行的代码。该代码非常糟糕。有一个类并不是真正的类,它的单个列表不包含成员变量;它实际上只是一个使用全局变量的函数集合,内存分配检查temp=new。。。;如果temp==NULL,但是new不能返回NULL,还有许多其他问题。@melpomene,先生,我是编程新手&我知道的不多,我只是在浏览网页,从任何可以获取内容的网站上学习。我没有太多的资源来确定代码的效率。这毫无意义。你认为打字是为了什么?
typedef struct node { ... } node; // C
int stat(const char *, struct stat *);
struct node *temp, *s;
temp = (struct node*) new(struct node);