这里是我得到分段错误的函数
void searchcity()
{
struct city *ptr=citylist;
printf("Which city would you like me to search?: ");
scanf("%s",searchedcity);
// printf("%s",searchedcity);
while(ptr)
{
if(!strcmp(searchedcity,ptr->name))
printf("name= %s, statecode = %s,population = %s,region = %s,zipcode = %s\n",ptr->name,ptr->statecode,ptr->population,ptr->region,ptr->zipcode);
else
printf("sorry, couldnt find that city");
ptr=ptr->next;
}
}
不确定是什么导致这种情况发生。
答案 0 :(得分:0)
基于该代码(a),以下是您需要检查的最低要求:
searchedcity
有足够的空间用于输入(b)。citylist
链接列表中保存的所有字符串都已正确构造(以null结尾)。你确实有一个其他问题,但与segfault没有任何关系。
您的代码将为列表中与您所在城市不匹配的每个节点打印"sorry, couldnt find that city"
,如果您有New York
,Moscow
和{ {1}},并且您查找London
,您会在找到该消息之前将其打印两次。
更好的解决方案(众多变体之一)将类似于:
London
这样,循环负责找到正确的指针或将其设置为NULL。 在之后,循环是决定应该打印什么的正确时间。
(a)除了危险的struct city *ptr = citylist;
while (ptr != NULL)
if (strcmp (searchedcity, ptr->name) == 0)
break;
if (ptr == NULL)
printf ("Sorry, couldnt find that city.\n");
else
printf ("%s, state = %s, pop = %s,r egion = %s, zip = %s\n",
ptr->name, ptr->statecode, ptr->population, ptr->region, ptr->zipcode);
之外,该代码本身似乎还可以,但它确实依赖于很多未显示的其他内容。
(b)实际上,scanf
带有无界scanf
是代码中的一个严重漏洞,很容易导致缓冲区溢出。有关详细信息和解决方案,请参阅here。在任何情况下,%s
都不是扫描带有空格的字符串的好方法,因为scanf("%s")
之类的内容最终会为Los Angeles
: - )
答案 1 :(得分:-1)
以下代码有效,我做了一些小改动,你可以通过它。你有很少的小错误是你的ptr->接下来由于缺少括号而从未被执行过。我在代码中写的其余部分。
谢谢我们的帮助。
#include <stdio.h>
struct city {
char name[100];
char statecode[100];
char population[100];
char region[100];
char zipcode[100];
struct city* next;
};
int main() // this is your searchcity function
{
char searchedcity[100]; // make sure you initialize this. YOu haven't done it in the code you gave us.
// Assume citylist is in your main function or initialized as a global var
// I initialized it here for simplicity
struct city* citylist = (struct city*) malloc(sizeof( struct city));
strcpy(citylist->statecode,"statecode");
strcpy(citylist->population,"population");
strcpy(citylist->region,"region");
strcpy(citylist->zipcode,"zipcode");
citylist->next = NULL;
//end of citylist
struct city *ptr = citylist;
printf("Which city would you like me to search?: ");
scanf("%s",searchedcity);
// printf("%s",searchedcity);
while(ptr) {
printf("while \n");
if(!strcmp(searchedcity,ptr->name)){
printf("name= %s, statecode = %s,population = %s,region = %s,zipcode = %s\n",ptr->name,ptr->statecode,ptr->population,ptr->region,ptr->zipcode);
}else{
printf("sorry, couldnt find that city");
ptr=ptr->next;
}
}
return 0;
}