-1

这是我得到分段错误的函数

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;
    }   
}

不知道是什么导致这种情况发生。

4

2 回答 2

0

根据该代码(a),您至少需要检查以下内容:

  • searchedcity有足够的空间用于输入(b)
  • citylist链表中保存的所有字符串均正确构造(以空结尾)。
  • 结构中的所有这些字段实际上都是字符数组(或等效指针)而不是整数(例如人口)。
  • 列表本身是正确构建的(没有悬空或无效指针)。

您确实还有另一个问题,尽管与段错误无关。

您的代码将为列表中与您的城市不匹配的每个节点打印,因此,如果您有"sorry, couldnt find that city",New YorkMoscow并且London您查找London,您将在找到之前打印两次该消息。

一个更好的解决方案(许多变体之一)是这样的:

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)事实上,scanf无界%s是代码中的一个严重漏洞,很容易导致缓冲区溢出。有关详细信息和解决方案,请参见此处。在任何情况下,scanf("%s")都不是扫描带有空格的字符串的好方法,因为类似的东西Los Angeles最终会变成Los:-)

于 2013-04-15T01:28:22.890 回答
-1

下面的代码有效,我做了一些小的改动,你可以通过它。您犯的几个小错误是您的 ptr->next 由于缺少括号而从未执行。其余的我写在代码中。

谢谢希望我们有所帮助。

#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;
}
于 2013-04-15T01:47:58.367 回答