[英]What's the difference between malloc and not using malloc when creating pointers to nodes of a linked list?
我的鏈表和節點定義如下:
struct node{
int item;
struct node *next;
};
struct linkedlist{
int size;
struct node *head;
};
struct linkedlist *L=(struct linkedlist*)malloc(sizeof(struct linkedlist));
使用有什么區別:
struct node *temp=malloc(sizeof(struct node));
temp=L->head;
和:
struct node *temp=L->head;
(不使用 malloc)
基本上,如果我將任何內容更改為臨時指針(例如 temp->item=3),它會在兩種情況下反映在原始鏈表 L 中嗎?
謝謝
struct node *temp=malloc(sizeof(struct node));
temp=L->head;
在這種情況下,您會丟失對malloc()
分配的內存塊的引用,並且您將無法free()
分配的內存(導致內存泄漏)。
它沒有意義,因為在分配內存后您更改了指針指向的位置。
對鏈表結構使用 malloc 沒有多大意義,但對節點來說確實有意義。
struct linkedlist L = {0, NULL}; // L is empty list
struct node *temp
temp = malloc(sizeof(struct node)); // allocate a node
temp->item = 2;
temp->next = L.head; // insert it to start of list
L.head = temp;
L.size += 1;
temp = malloc(sizeof(struct node)); // allocate another node
temp->item = 1;
temp->next = L.head; // insert it to start of list
L.head = temp;
L.size += 1;
temp = malloc(sizeof(struct node)); // allocate another node
temp->item = 0;
temp->next = L.head; // insert it to start of list
L.head = temp;
L.size += 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.