【问题标题】:Dynamic memory Allocation in Linked list insert function链表插入函数中的动态内存分配
【发布时间】:2021-09-20 16:51:35
【问题描述】:

我正在阅读有关 C++ 链接列表的教程。我发现以下代码用于在链接列表中插入元素的实现:

/* Given a reference (pointer to pointer) to the head
of a list and an int, appends a new node at the end */
void append(Node** head_ref, int new_data)
{
    /* 1. allocate node */
    Node* new_node = new Node();
 
    Node *last = *head_ref; /* used in step 5*/
 
    /* 2. put in the data */
    new_node->data = new_data;
 
    /* 3. This new node is going to be
    the last node, so make next of
    it as NULL*/
    new_node->next = NULL;
 
    /* 4. If the Linked List is empty,
    then make the new node as head */
    if (*head_ref == NULL)
    {
        *head_ref = new_node;
        return;
    }
 
    /* 5. Else traverse till the last node */
    while (last->next != NULL)
        last = last->next;
 
    /* 6. Change the next of last node */
    last->next = new_node;
    return;
}

在第 1 步中,我们声明了一个名为 new_node 的指针,它指向一个动态创建的块。

我无法理解的是,如果函数被调用 4 次,那么如何在每次调用时创建一个具有相同名称的新指针变量?由于我们使用的是动态内存分配,所以当我们从函数返回时它不会被转储。

那么,这段代码是如何工作的?

【问题讨论】:

  • 因为这是按设计工作,而其他一些函数负责deleteing 链表中的所有内存?
  • new 不创建变量;它创建对象。 new_node 与任何其他局部变量没有区别;它恰好指向一个具有动态生命周期的对象。

标签: c++ pointers linked-list dynamic-memory-allocation


【解决方案1】:

变量名在运行时不存在,仅在编译时存在。

new_node 变量表示append() 函数的本地内存块。每次调用append() 时,都会在进入作用域时创建一个新的内存块,当它超出作用域时会释放该块。

每次调用new 都会分配一个新的动态内存块。在这种情况下,该块的内存地址存储在 new_node 表示的本地内存块中。

     append()                         
+----------------+                     
|   new_node     |                     
| +------------+ |      +-------------+
| | 0xABCDABCD |-|------| Node object |
| +------------+ |      +-------------+
+----------------+                                                           

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-08
    • 2019-10-14
    • 2014-09-29
    • 2013-11-10
    • 2021-01-03
    • 2017-08-17
    • 2013-01-23
    • 2013-04-14
    相关资源
    最近更新 更多