gpt4 book ai didi

c - 创建指向链表节点的指针时,malloc 和不使用 malloc 有什么区别?

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:31 24 4
gpt4 key购买 nike

我的链表和节点定义如下:

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),对于这两种情况,它会反射(reflect)在原始链表 L 中吗?

谢谢

最佳答案

对链表结构使用 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;

关于c - 创建指向链表节点的指针时,malloc 和不使用 malloc 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33676421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com