链表插入函数中的动态内存分配
Dynamic memory Allocation in Linked list insert function
我正在阅读有关 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 次,那么如何在每次调用时都创建一个具有相同名称的新指针变量?由于我们使用的是动态内存分配,因此当我们从函数中 return 时它不会被转储。
那么,这段代码是如何工作的?
变量名在运行时不存在,只在编译时存在。
new_node
变量表示 append()
函数本地的一块内存。每次调用 append()
时,都会在进入作用域时创建一个新的内存块,并在离开作用域时释放该块。
每次调用 new
都会分配一个新的动态内存块。在这种情况下,该块的内存地址存储在 new_node
代表的本地内存块中。
append()
+----------------+
| new_node |
| +------------+ | +-------------+
| | 0xABCDABCD |-|------| Node object |
| +------------+ | +-------------+
+----------------+
我正在阅读有关 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 次,那么如何在每次调用时都创建一个具有相同名称的新指针变量?由于我们使用的是动态内存分配,因此当我们从函数中 return 时它不会被转储。
那么,这段代码是如何工作的?
变量名在运行时不存在,只在编译时存在。
new_node
变量表示 append()
函数本地的一块内存。每次调用 append()
时,都会在进入作用域时创建一个新的内存块,并在离开作用域时释放该块。
每次调用 new
都会分配一个新的动态内存块。在这种情况下,该块的内存地址存储在 new_node
代表的本地内存块中。
append()
+----------------+
| new_node |
| +------------+ | +-------------+
| | 0xABCDABCD |-|------| Node object |
| +------------+ | +-------------+
+----------------+