我正在用 C 撰寫一個單鏈表,但無法理解以下代碼。
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
int main() {
/*Say I allocate this list to say 1->2->3->4->NULL*/
ListNode* node = malloc(sizeof(ListNode));
ListNode* n1 = node; // An ordinary pointer
ListNode* n_heap = malloc(sizeof(ListNode)); // A heap allocated pointer
n_heap = node->next; // 2->3->4->NULL
n1->next = NULL;
}
現在從上面的例子中,我假設n_heap也是NULL如此。但即使經過n1->next = NULL;,n_heap依舊2->3->4->NULL。那么是node->next復制到的n_heap嗎?還是n_heap現在指向原來的堆所在的位置node->next,而n1->next現在設定為NULL?這是否意味著node最初不是node->next資料的所有者?
uj5u.com熱心網友回復:
int main() { /*Say I allocate this list to say 1->2->3->4->NULL*/ ListNode* node = malloc(sizeof(ListNode));
node是指向動態分配資料的指標。在具有堆疊/堆區別的 C 實作上,這將在堆上。
ListNode* n1 = node; // An ordinary pointer
n1現在指向相同的動態分配資料node。它并不比node現在更多或更少“普通”。
ListNode* n_heap = malloc(sizeof(ListNode)); // A heap allocated pointer
(成功時)n_heap指向不同的動態分配資料。指標本身具有與 and 相同的范圍和存盤持續時間,node并且n1與它們一樣“普通”。
n_heap = node->next; // 2->3->4->NULL
現在n_heap之前指向的記憶體被泄露了,因為沒有指向它的指標。 n_heap指向相同的記憶體node->next。這是相同的記憶n1->next。
n1->next = NULL;
現在,作為(以及作為)可訪問的指標物件的值設定為 NULL。這對該指標物件先前指向的資料沒有影響,對仍指向相關資料的變數也沒有影響。n1->nextnode->nextn_heap
}現在從上面的例子中,我假設
n_heap也是NULL如此。但即使經過n1->next = NULL;,n_heap依舊2->3->4->NULL。
您無法區分指標物件和它們的值指向的物件。賦值NULL給n1->next設定一個指標物件的值。它對舊指標值指向的物件沒有任何作用。它對指向同一物件的其他不同點沒有任何作用。另一方面,n_heap is not 2->3->4->NULL,它是一個與所有節點不同的指標,其值指向包含 的節點2。
那么node->next是復制到n_heap了嗎?
是的,這就是作業的作用,但不是我認為你的意思。同樣,分配將n_heap = node->next存盤在的指標值復制node->next到n_heap. 這兩個不同的指標物件都包含指向相同資料的值。
or is it that
n_heapnow points to the original heap locatednode->next, and then1->nextnow set toNULL?
Yes and no. Again, neither the object designated by n_heap nor the onje designated by node->next contain the data you are describing as 2->3->4->NULL. Instead, they both contain the address of the node containing the first of those values.
Does this mean
nodewasn't initially the owner ofnode->nextdata?
It depends on what you mean by "owner". Certainly neither node nor *node is a container of the data to which node->next points. As the term "owner" is usually applied to pointers, it is about responsibility for freeing the pointed to data, not about storage layout. Responsibility to free is a question of data and control flow in the program, not a property of the data itself.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434831.html
