这是我遇到段错误的函数
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;
}
}
不确定是什么原因导致这种情况发生。
最佳答案
根据该代码(a),您至少需要检查以下内容:
searchedcity
有足够的空间用于输入(b)。citylist
链表中保存的所有字符串均已正确构造(以 null 结尾)。- 结构中的所有字段实际上是字符数组(或等效的指针),而不是整数(例如人口)。
- 列表本身已正确构建(没有悬空或无效指针)。
您确实还有另一个问题,尽管与段错误无关。
您的代码将为列表中与您的城市不匹配的每个节点打印“抱歉,找不到该城市”
,因此,如果您有纽约
、莫斯科
和伦敦
,并且您寻找伦敦
,您会在找到该消息之前打印两次该消息.
更好的解决方案(众多变体之一)如下:
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);
这样,循环负责找到正确的指针或将其设置为 NULL。 之后循环是决定应该打印什么的正确时间。
<小时/>(a) 除了危险的 scanf
之外,该代码本身看起来还不错,但它确实依赖于很多未显示的其他内容。
(b) 事实上,带有无界 %s
的 scanf
是代码中的一个严重漏洞,很容易导致缓冲区溢出。请参阅here了解详细信息和解决方案。无论如何,scanf("%s")
都不是扫描带有空格的字符串的好方法,因为像 Los Angeles
这样的内容最终会变成 Los
:-)
关于C语言,段错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006283/