结构变量的动态分配
Dynamic Allocation of Structure variable
下面是我学到的动态内存分配方法,
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 { ... };
时,它会创建两个类型名称,node
和struct 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是一个结构节点指针,所以我们需要在赋值之前对其进行类型转换。。
相关文章:
- 动态分配Q_Property变量
- 在C++中动态分配变量类型
- 为什么动态分配的两个变量的内存位置不是连续的?
- C :动态分配的变量未在clang中删除
- 在 CPP 中动态分配变量的数据类型
- 结构变量的动态分配
- 在使用动态分配的变量和_chdir Windows功能时损坏的堆
- 如果我将内存动态分配给静态变量,我应该释放它还是会自动释放它
- 动态分配的成员变量。有什么意义?
- 对齐的成员变量和动态分配
- 动态分配的静态变量
- 尝试使用成员函数访问动态分配的成员变量时读取访问冲突
- 对于数据成员,如果包含对象已在动态内存中,则动态分配此变量(或不动态分配)之间是否有任何区别
- 如何为字符串数组实例变量动态分配空间
- 对动态分配的变量的引用与指向相同动态分配变量的指针
- C++动态内存分配.将动态分配的 char* 返回变量数组分配给 char 变量
- 在 c++ 中声明变量与动态为变量分配内存
- c++动态分配变量,执行的流程是什么
- 在C++解释器中动态分配变量的最佳方式
- 动态分配变量的作用域