结构和指向结构的指针之间的区别
The difference between struct and a pointer to struct
假设我有一个如下声明的结构:
struct node{
node *next;
int data;
}
我在class Stack
中有一个C++函数,它定义了push
操作,比如:
void Stack::push(int n){
node *temp = new node;
temp->data = n;
temp->next = top;
top = temp;
if(topMin == NULL) {
temp = new node;
temp->data = n;
temp->next = topMin;
topMin = temp;
return;
}
if(top->data < topMin->data) {
temp = new node;
temp->data = n;
temp->next = topMin;
topMin = temp;
}
return;
}
使用有什么区别
node *temp = new node;
和
temp = new node;
在上面的代码中?更具体地说,我对其含义感到困惑。如果温度是pointer(*)
,我理解
temp->data
只是取消引用指向结构((*temp).data
(的指针。类似地,使用temp = new node
意味着什么?
这只是代表性的差异吗?
node *temp = new node;
正在声明temp
并对其进行初始化,而
temp = new node;
正在分配给一个已经声明的变量,因此编译器已经知道它是什么类型。
第一个在本地作用域中声明一个名为"temp"的新变量,并将其初始化为指向动态作用域中对象的新实例。
第二个初始化名为"temp"的现有变量,以指向动态范围中对象的新实例。变量的现有内容将被销毁。
与您的问题无关:显示的代码可能存在内存泄漏。
没有区别。它们是相同的变量。
此处:
node *temp = new node;
您已经将temp
声明为node*
,并使用new
分配内存,然后将分配的内存分配给它。
temp = new node;
您分配了新内存,并将内存地址分配给temp
,它仍然是node*
。
相关文章:
- 大小相等但成员数量不同的结构之间的性能差异
- 旧版c++中结构和类之间的差异
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- 不同的类或结构初始化方法之间的性能差异是什么?
- 为什么不同类型层次结构的指针之间的dynamic_cast定义得很好?
- 在.cpp文件之间传递结构声明,而不使用全局头文件
- 在两个结构之间共享数组
- 关于SFINAE的函数和结构之间的差异
- 在结构之间复制字符数据
- 在几乎相同的结构之间传递成员值
- 在结构之间复制特定值
- 警告MSB3270:项目的处理器体系结构之间的不匹配
- 抽象数据类型(ADT)和数据结构之间有什么区别
- 难以调用函数和结构之间的信息
- 在结构C++之间传递数组
- 类和结构之间的差异
- 这些不同的对象结构之间有什么区别
- C++类和结构之间交互的语法
- 集合的结构之间的比较
- 在体系结构之间可移植的有符号二进制表示形式