gpt4 book ai didi

C - 显示期间链表段错误

转载 作者:行者123 更新时间:2023-11-30 20:23:55 25 4
gpt4 key购买 nike

编辑 2:我意识到对于不在数据库中的任何查询,我都没有“未找到”结果。已进行更改以引入此功能。这是当前的测试和测试输出:

输入:

3
sam
99912222
tom
11122222
harry
12299933
sam
edward
harry

输出:

Not found

=0
Not found

=0
Not found

=0
Not found

=0
sam
=99912222
Not found

=0
Not found

=0
Not found
[Infinite loop continues]
<小时/>

编辑:我在 display() 的 while 循环中更改了一些内容。我现在得到一个无限循环打印“=0”,除了搜索的第三个或第四个循环。嗯...

顺便说一句,感谢您提醒使用 == 测试字符串。现在看来是理所当然的。

<小时/>

我已经做了一些搜索,但还无法理解我的代码哪里出了问题。我正在进行一项挑战,该挑战将产生一个简单的电话簿程序。它将输入一个数字(要添加的条目数),然后输入姓名和关联的电话号码(没有破折号或句点)。添加条目后,用户可以按名称搜索条目,并以“名称=编号”的格式显示编号。

代码在 display() 函数中的 while 循环中抛出段错误。我假设我正在尝试打印分配为 NULL 的内容,但我无法弄清楚哪里出了问题。任何帮助将不胜感激。

最后,挑战要求我阅读查询直到 EOF;然而,这让我很困惑,因为我要接受来自标准输入的用户输入。 EOF 对于 stdin 来说是什么样的,只是一个寄存器返回 (\n)?

(PS:这是我第一次尝试链接列表,因此我们将不胜感激。)

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

void add_entry(void);
void display(void);

struct phonebook {
char name[50];
int number;
struct phonebook *next;
};
struct phonebook *firstp, *currentp, *newp;
char tempname[50];

int main() {
int N;
firstp = NULL;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
add_entry();
}
display();

return 0;
}

void add_entry(void) {
newp = (struct phonebook*)malloc(sizeof(struct phonebook));
if (firstp == NULL) firstp = currentp = newp;
else {
currentp = firstp;
while (currentp->next != NULL)
currentp = currentp->next;
currentp->next = newp;
currentp = newp;
}
fgets(currentp->name, 50, stdin);
scanf("%d", &currentp->number);

currentp->next = NULL;
}

void display(void) {
while (strcmp(tempname, "\n") != 0) {
currentp = firstp;
fgets(tempname, 50, stdin);

while (strcmp(currentp->name, tempname) != 0) {
if (currentp->next == NULL) {
printf("Not found\n");
break;
}
currentp = currentp->next;
}
printf("%s=%d\n", currentp->name, currentp->number);
}
}

最佳答案

您的问题是您永远找不到您要查找的条目。表达式 currentp->name != tempname 将始终为 true,因为它们始终不相等。在 C 中,此相等性测试不会编译为逐个字符的比较,而是编译为指向 currentp->nametempname 的指针的比较。由于它们永远不会位于相同的地址,因此它们永远不会相等。

尝试!strcmp(currentp->name, tempname)

那么,你崩溃的原因是因为你到达了列表的末尾,因此在循环之后currentp将为NULL,然后你尝试打印NULL->nameNULL->number,实际上导致了崩溃。

此外,另一方面,您可能希望开始使用局部变量,而不是对所有内容都使用全局变量。

关于C - 显示期间链表段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35028353/

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