-4

出于某种原因,我无法正常工作。这是我在代码中的功能,如果这还不够帮助,我会很乐意发布整个代码。

char addcity()
{
    citylist=malloc(sizeof(struct city));
    struct city *temp;
    char addcity[50];
    char addstate[50];
    char addpopulation[50];
    char addregion[50];
    char addzipcode[50];
    //temp = citylist;
    //citylist=malloc(sizeof(struct city));
    //struct city *ptr=citylist;
    struct city *ptr= (struct city*)malloc(sizeof(struct city));
    printf("Which city would you like to add?: ");
    scanf("%s",addcity);
    printf("Which state is the city in?: ");
    scanf("%s",addstate);
    printf("What is the population?: ");
    scanf("%s", addpopulation);
    printf("what is the region?: ");
    scanf("%s", addregion);
    printf("what is the zipcode?: ");
    scanf("%s", addzipcode);
    int found;
    ptr->name=addcity;
    ptr->statecode=addstate;
    ptr->population=addpopulation;
    ptr->region=addregion;
    ptr->zipcode=addzipcode;
    ptr->next=NULL;

    curr->next=ptr;
    curr=ptr;

    printlist();  //this just prints out the whole list.

有时我得到一个分段错误,而其他时候它根本不起作用。我必须使用 strcpy(a,b) 来复制字符串吗?

4

3 回答 3

2
printf("Which city would you like to add?: ");
scanf("%s",&ptr->name);
printf("Which state is the city in?: ");
scanf("%s",&ptr->statecode);
printf("What is the population?: ");
scanf("%s",&ptr->population);
printf("what is the region?: ");
scanf("%s",&ptr->region);
printf("what is the zipcode?: ");
scanf("%s",&ptr->zipcode);
于 2013-04-19T05:18:39.670 回答
1
printf("Enter String ::");
scanf("%s",&ptr->str); 
于 2013-04-19T04:32:58.280 回答
1

您的代码中有一些问题。您的第一个问题是您在结构中设置指针以指向局部变量。一旦代码离开addcity(),这些局部变量将不再有效,任何试图使用它们的东西都会遇到麻烦。

要将本地字符串复制到您的结构中,您需要使用某种形式的字符串复制功能,例如strcpy(a,b).

于 2013-04-18T20:19:28.380 回答