嗨,我正在尝试编写一个程序,该程序将返回最小值链表并获取 5 个节点的链表 我已经使用调试器运行了它,我注意到由于某种原因,当我将第一个节点发送到我的“搜索列表”函数时,地址和数字值只是垃圾,所以我做错了什么? 为我辩护,我是 c 新手:)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct item {
int num;
struct item *next;
}item;
struct item *addList(struct item **first, int num);
int searchList(struct item *first);
int main() {
struct item *first = malloc(sizeof(struct item));
int n, i;
printf("Enter 5 numbers: ");
for (i = 0; i < 5; i++) {
scanf("%d", &n);
first = addList(&first, n);
}
printf("%d", searchList(first));
}
struct item *addList(struct item **first, int n) {
struct item *new_node ;
new_node = malloc(sizeof(struct item));
if (new_node == NULL)
{
printf("/nError, cant allocate memory (addList Function).");
exit(1);
}
new_node->num = n;
new_node->next = *first;
*first = new_node;
}
int searchList(struct item *first) {
struct item *p;
int min=first->num;
if (first == NULL)
return 0;
for (p = first; p != NULL; p = p->next) {
if (p->num < min)
min = p->num;
}
return min;
}
最佳答案
addList()
应该返回一个值并将其分配给 main()
中的 first
。但你没有返回任何东西。但是您不需要从 addList()
返回任何内容,因为您正在通过指向指针的指针修改指针first
。因此,请将其设为返回 void
的函数,并且不要将 addList()
的返回值分配给 first
。
您期望列表以 NULL 指针终止。所以,改变一下
struct item *first = malloc(sizeof(struct item));
至
struct item *first = NULL;
这既修复了内存泄漏并确保列表末尾是 NULL 指针。
关于c - 发送链表到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41620977/