【发布时间】:2018-10-13 20:40:26
【问题描述】:
如何在链表生成中使用 malloc?我看不到它是如何用于生成新链表的,而不是为链表保留内存
提示:按Ctrl + F 并查找“(***)”(不带引号)以找到确切的代码位置
示例 1:
#include <stdio.h>
#include <stdlib.h>
struct LinkedList {
int data; /* The data part of the linked list */
struct LinkedList *next; /* The pointer part of the linked list */
};
int main(void) {
/* Generate the 1st node ("head") */
struct LinkedList *head /* I am not sure what this pointer */
head = NULL; /* is doing to the struct*/
head = malloc(sizeof(struct LinkedList)); /* Head points to null. Now
* malloc() is being called
* and is assigned to head.
* Next line implies head is
* already pointing to a
* linked list, which means
* malloc() is making a new
* strucuture (***) */
/* Generate the second node */
head -> data = 1; // This implies head is already pointing to a linked list
head -> next = malloc(sizeof(struct LinkedList));
/* Generate the third node */
head -> next -> data = 2;
head -> next -> next = malloc(sizeof(struct LinkedList));
/* Generate the fourth node */
head -> next -> next -> data = 3;
head -> next -> next -> next = NULL;
return 0;
}
示例 2:
#include<stdio.h>
#include<stdlib.h>
struct LinkedList {
int data;
struct LinkedList *next;
}; // notice the semi-colon!
int main(void) {
struct LinkedList *head = NULL; /* why is it doing this? */
struct LinkedList *second = NULL;
struct LinkedList *third = NULL;
// Generate the node structure:
/* how does (struct LinkedList*) affect malloc? (***) */
head = (struct LinkedList*)malloc(sizeof(struct LinkedList));
second = (struct LinkedList*)malloc(sizeof(struct LinkedList));
third = (struct LinkedList*)malloc(sizeof(struct LinkedList));
// Now fill the first node with info:
head->data = 1; /* assign data to the first node */
head->next = second; /* Link the first node ("head") with the second
* node ("second") */
// Now fill the second node with info:
second->data = 2; /* assign data to the second node */
second->next = third; /* Link the second node to the third node */
// Now fill the second node with info:
third->data = 3; /* assign data to the second node */
third->next = NULL; /* Since node 3 is our last node to the link list,
* we give it the value of NULL */
return 0;
}
教科书将链表描述为链式结构。 Malloc() 用于动态内存管理。但是,在这些示例中,malloc 被用于声明一个新结构,我不明白为什么。我以为它只保留内存
例如,在示例 1 中,malloc() 为结构保留空间,但不“创建”它(struct LinkedList var 将创建一个新的链表并将其存储在 var 中)
例如,在示例 2 中,malloc() 似乎受到(struct LinkedList*)(即(struct LinkedList*)malloc(sizeof(struct LinkedList));)的影响,但我不确定
【问题讨论】:
-
malloc未被用于“声明”该代码中的任何内容。它被调用以在堆上分配存储。链表中的节点是指针的结构。必须分配内存来保存指针指向的节点。 -
没有必要从
malloc转换返回值,但这基本上是示例2 中代码所做的,将malloc返回的void*转换为类型struct LinkedList*。跨度> -
请注意,
calloc可用于分配所需的存储空间并将内存清除为零,因此在需要另一个节点之前,所有指针都已经为 NULL,您只需初始化数据元素。