gpt4 book ai didi

c - 链表 C 程序不产生输出

转载 作者:太空宇宙 更新时间:2023-11-04 07:15:13 25 4
gpt4 key购买 nike

我正在阅读链表,我能找到的唯一好的来源是斯坦福计算机科学图书馆。我希望实现我从中学到的东西,并在我的编译器上运行它。该程序是查找{1,2,3}链表中元素的个数。

#include <stdio.h>
#include <stdlib.h>

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

int main()
{
struct node* BuildOneTwoThree()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;

head = malloc(sizeof(struct node)); // allocate 3 nodes in the heap
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));

head->data = 1; // setup first node
head->next = second; // note: pointer assignment rule

second->data = 2; // setup second node
second->next = third;

third->data = 3; // setup third link
third->next = NULL;

return head;

int Length(struct node* head)
{
struct node* current = head;
int count = 0;

while (current != NULL)
{
count++;
current = current->next;
}

printf("%d",count);
return count;
}

}
return 0;
}

返回空白。我不明白O错在哪里,我做错了什么?

最佳答案

首先,您试图在 main() 函数中定义函数。 BuildOneTwoThree 是在 main 中定义的,而 Length 似乎是在 BuildOneTwoThree 中定义的。你为什么那样做? C语言没有这个功能。您不能嵌套函数定义。所有功能都必须在文件级别单独定义。

其次,您永远不会调用您定义的任何函数。您的 main() 函数除了 return 0; 之外什么都不做。

看看任何有效的 C 程序,您应该立即弄清楚函数应该如何定义。请注意,虽然某些编译器支持嵌套函数定义作为非标准扩展,但您仍然必须在某些时候调用您的函数。

关于c - 链表 C 程序不产生输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25415401/

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