C 链表程序崩溃
我使用structs实现了一个包含3个元素的链表。在我引入函数来计算链表中的元素数之前,它工作得很好。下面是C语言程序的代码 CC 链表程序崩溃,c,linked-list,C,Linked List,我使用structs实现了一个包含3个元素的链表。在我引入函数来计算链表中的元素数之前,它工作得很好。下面是C语言程序的代码 C #include <stdlib.h> #include <stdio.h> struct node{ int data; struct node* next; }; struct node* Linked_list(); int Length(); int main() { int length; Li
#include <stdlib.h>
#include <stdio.h>
struct node{
int data;
struct node* next;
};
struct node* Linked_list();
int Length();
int main()
{
int length;
Linked_list();
length = Length();
printf("%d", length);
}
struct node* Linked_list() {
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;
printf("%d %d", head->data, second->data);
}
int Length(struct node* head){
struct node* current = head;
int count = 0;
while(current!=NULL)
{
count++;
current = current->next;
}
return count;
}
#包括
#包括
结构节点{
int数据;
结构节点*下一步;
};
结构节点*链接列表();
int Length();
int main()
{
整数长度;
链表();
长度=长度();
printf(“%d”,长度);
}
结构节点*链接列表(){
结构节点*head=NULL;
结构节点*second=NULL;
结构节点*third=NULL;
head=malloc(sizeof(结构节点));
第二个=malloc(sizeof(struct node));
第三个=malloc(sizeof(struct node));
头部->数据=1;
头->下一个=秒;
第二->数据=2;
第二->下一个=第三个;
第三->数据=3;
第三->下一步=空;
printf(“%d%d”,头部->数据,第二个->数据);
}
整数长度(结构节点*头){
结构节点*当前=头部;
整数计数=0;
while(当前!=NULL)
{
计数++;
当前=当前->下一步;
}
返回计数;
}
您正在声明和调用Length()
,因为它没有参数Length=Length()代码>
但当您定义它时,它确实有一个参数:
int Length(struct node* head)
这是合法的,但实际函数没有使用head
参数,这就是它崩溃的原因
您应该从Linked_list()
(当前未返回任何内容)返回head
,并将其馈送到Length()
然后在主屏幕上:
struct node* head = Linked_list();
length = Length(head);
不过可能还有其他问题。在调试器中运行,错误是什么,whathaveyoutried.com,等等。length=length();没有参数?它没有显示错误,但在输出链表的第一个和第二个数据元素后崩溃。也就是说,它正确地执行了第一个函数。@djechlin它没有显示任何错误。@SumitGera-您使用什么来构建/运行它?它为我编译并运行,数据元素的输出为12
,长度的输出为0
(由于您没有传入头,所以应该是这样),谢谢。但是,是否有必要在函数int Length()
中包含输入参数类型?这是一种很好的做法,您应该这样做,但为了与较旧的C
版本兼容,编译器允许您不这样做。程序现在运行正常。谢谢
struct node* head = Linked_list();
length = Length(head);