结构和指向结构的指针之间的区别

The difference between struct and a pointer to struct

本文关键字:结构 之间 区别 指针      更新时间:2023-10-16

假设我有一个如下声明的结构:

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*