gpt4 book ai didi

c - 为什么这个链表代码总是导致 head 为空?

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

我已经实现了一个短链接列表代码以添加到列表的开头。

但是头部总是包含NULL。我真的不明白为什么它会这样。任何帮助表示赞赏!下面是代码:

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
int iData;
struct node *next;
} Node;

void add2Beg(Node* head, int num);


int main(int argc, char const *argv[])
{
Node *head = NULL;
add2Beg(head, 5);
if (head == NULL)
printf("nothing in head !!!\n");
else{
printf("not null\n");
}
add2Beg(head, 15);
return 0;
}

//adds to the beginning of the linked list
void add2Beg(Node* head, int num)
{
//create a temporary location to hold the new entry
Node* temp = (Node *)malloc(sizeof(Node));
temp->iData = num;

if(head == NULL)
{
head = temp;
printf("inside add2Beg\n");
printf("%d\n", head->iData);
head->next = NULL;
printf("exiting add2Beg\n");
}
else
{
temp->next = head;
printf("%p\n", temp->next);
head = temp;
}

}

最佳答案

因为 add2Beg() 中的 head 变量是该函数的本地变量。为其分配一个新的指针值 (head = temp;) 只会更改 函数内的 head 变量。您需要传入一个指向指针的指针:

void add2Beg(Node** head, int num)

然后在函数内部使用*head:

if(*head == NULL)
{
*head = temp;

小心像 head->next = NULL; 这样的行——这应该被重写为 (*head)->next = NULL; (**head).next = NULL;.

等等。然后像这样调用函数:

add2Beg(&head, 15);

关于c - 为什么这个链表代码总是导致 head 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12519181/

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