我是新來的鏈接列表,但我試圖創建一個鏈接列表和3個元素,並且編寫一個函數來計算所述鏈接列表中的元素數量。 我不斷收到分段錯誤,但我找不出原因。 任何幫助將是最受歡迎的。當鏈接列表中的元素計數時出現分段錯誤
#include <stdio.h>
#include <stdlib.h>
typedef struct node { // create a struct to build a
int data; // linked list
struct node* next;
};
struct node* BuildOneTwoThree() {
struct node* head = NULL; // pointers
struct node* second = NULL; // for
struct node* third = NULL; // linked list
// allocate memory on the heap for the 3 nodes
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 1; // set up 1st node
head->next = second;
second->data = 2; // set up 2nd node
second->next = third;
third->data = 3; // set up 3rd node
third->next = NULL;
return head;
}
void main(){
int num = Length(BuildOneTwoThree);
printf("Number of nodes:%d\n", num);
}
int Length(struct node* head) {
struct node* current = head;
int count = 0;
while(current != NULL) {
count++;
current = current->next;
}
return count;
}
在調試器中運行它並查看它發生故障的位置。 –