我一直在阅读斯坦福大学关于链表的教程。我使用了其中一个函数来创建三个数字(1,2,3)的列表。函数本身不会打印结果,所以我决定自己测试它。但是,当我运行它时,它给了我分段错误。
话虽如此,当我删除函数并将代码复制到 main 时,它可以工作。有人可以解释为什么主要功能不起作用吗?
这是给我分段错误的代码:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* BuildOneTwoThree()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
return head;
}
int main()
{
struct node* head;
struct node* second;
struct node* third;
struct node* next;
int data;
BuildOneTwoThree();
struct node* current = head;
while(current != NULL)
{
printf("%d ", current->data );
current= current->next;
}
}
这个工作:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
int main()
{
int data;
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
struct node* current = head;
while(current != NULL)
{
printf("%d ", current->data );
current= current->next;
}
}
在不工作的版本中,您将忽略 BuildOneTwoThree
的返回值,并将未初始化的局部变量从 main
head
(与BuildOneTwoThree
作用域中同名的局部变量不同)分配给变量current
。
因此,打印代码应使用:
struct node* head = BuildOneTwoThree();
current = head;
相反,利用在 BuildOneTwoThree()
中分配的head
节点,并分配给main
的头指针。