Ich bin neu in verknüpften Listen, aber ich versuche, eine verknüpfte Liste mit 3 Elementen zu erstellen und eine Funktion zu schreiben, die die Anzahl der Elemente in der verknüpften Liste zählt. Ich bekomme immer einen Segmentierungsfehler, aber ich kann nicht herausfinden warum. Jede Hilfe wäre sehr willkommen.Segmentierungsfehler beim Zählen von Elementen in der verknüpften Liste
#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;
}
Führen Sie es in einem Debugger und sehen Sie, wo es fehlerhaft ist. –