【发布时间】:2016-01-27 03:30:42
【问题描述】:
编辑 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”,除了通过搜索的第三个或第四个循环。嗯……
顺便说一句,感谢您提醒使用== 测试字符串。现在看起来很容易。
我进行了一些搜索,但仍然无法理解我的代码哪里出错了。我正在处理一项挑战,这将导致一个简单的电话簿程序。它将输入一个数字(要添加的条目数),然后是名称和相关的电话号码(没有破折号或句点)。添加条目后,用户可以按名称搜索条目,并以“name=number”格式显示数字。
代码在 display() 函数中使用 while 循环引发分段错误。我假设我正在尝试打印分配为 NULL 的内容,但我无法弄清楚我哪里出错了。任何帮助将不胜感激。
最后,挑战要求我在 EOF 之前阅读查询;但是,这让我感到困惑,因为我要接受来自标准输入的用户输入。标准输入的 EOF 是什么样的,只是一个寄存器返回 (\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", ¤tp->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);
}
}
【问题讨论】:
-
这里有一个指针:
int n = 0; int *pointer = &n;。我总是很乐意提供帮助:)
标签: c linked-list segmentation-fault