gpt4 book ai didi

c - 计算链表中的元素时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:53 24 4
gpt4 key购买 nike

我是链表的新手,但我正在尝试创建一个包含 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;
}

最佳答案

线

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;
};

是不对的。这会产生 useless storage class specifier in empty declaration 警告。这需要要么

struct node {
int data;
struct node* next;
};

struct node {
int data;
struct node* next;
} node;

另外,main的返回类型需要是int,而不是void

关于c - 计算链表中的元素时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39060018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com