-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

コードにいくつかの問題があります。最初の問題は、ローカル変数を指すように構造体にポインターを設定していることです。コードが を離れるaddcity()と、それらのローカル変数は無効になり、それらを使用しようとすると問題が発生します。

ローカル文字列を構造体にコピーするには、何らかの形式の文字列コピー関数 ( strcpy(a,b).

于 2013-04-18T20:19:28.380 に答える
1
printf("Enter String ::");
scanf("%s",&ptr->str); 
于 2013-04-19T04:32:58.280 に答える