我是链接列表的新手,但我正在尝试创建一个包含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;
}
答案 0 :(得分:3)
该行
int num = Length(BuildOneTwoThree);
需要
int num = Length(BuildOneTwoThree());
^^^ Missing the function call.
没有它,你只是将函数指针指向Length
。
您可以在使用之前提供函数声明来避免此类错误。
struct node* BuildOneTwoThree();
int Length(struct node* head);
使用在文件顶部声明的函数,我从gcc获得以下消息:
soc.c: In function ‘main’:
soc.c:36:22: warning: passing argument 1 of ‘Length’ from incompatible pointer type [-Wincompatible-pointer-types]
int num = Length(BuildOneTwoThree);
^
soc.c:10:5: note: expected ‘struct node *’ but argument is of type ‘struct node * (*)()’
int Length(struct node* head);
typedef struct node {
int data;
struct node* next;
};
不对。这会在空声明警告中生成无用的存储类说明符。那需要是
struct node {
int data;
struct node* next;
};
或
struct node {
int data;
struct node* next;
} node;
此外,main
的返回类型必须为int
,而不是void
。
答案 1 :(得分:2)
您需要在&#39; main&#39;
中更改此行int num = Length(BuildOneTwoThree);
到
int num = Length(BuildOneTwoThree());
目前,当您将此文件编译为&#39;长度&#39;时,您的编译器应该抛出错误。函数期待一个结构节点*&#39;但是你传给它一个函数指针。