0

编译器没有出现任何错误......它应该是一个基本的电话簿,有 5 个插槽供人们使用。出于某种原因,一切似乎都可以正常工作,但它并没有保存信息。我做错了什么?

typedef struct contact{
  char fname[10];
  char lname[10];
  int pnumber;
};

struct contact p1;
struct contact p2;
struct contact p3;
struct contact p4;
struct contact p5;

int go =0;

int phonebook(struct contact person,int use);

int main(){
 while(go == 0){
   int contact;
   int choice;
   int location;

   printf("first what position in your contacts would you like to change?(1-5)\n");

   scanf("%d",&location);

   printf("what would you like to do?\n1. add a contact\n2. change a contact\n3. print  a 

   contact\n4. Quit\n");

   scanf("%d",&choice);

   switch(location){
    case 1:
     phonebook(p1,choice);
     break;
    case 2:
     phonebook(p2,choice);
     break;
    case 3:
     phonebook(p3,choice);
     break;
    case 4:
     phonebook(p4,choice);
     break;         
    case 5:
     phonebook(p5,choice);
     break;
    default:
     printf("that was not a valid option\n");
  } 
 }

 system("PAUSE");
 return EXIT_SUCCESS;
}

int phonebook(struct contact person,int use){
  switch(use){
   case 1:
    if(person.pnumber>0){ 
      printf("you already have a contact there\n");
    }
    else{
      printf("What is the contact's first name?\n"); 
      scanf("%s", &person.fname);
      printf("\nWhat is the contact's last name?\n");
      scanf("%s", &person.lname);
      printf("\nWhat is the contact's phone number?\n");
      scanf("%d", &person.pnumber);
    }
   break;
  case 2:
   if(person.pnumber == 0)
     printf("No contact is saved in this position\n");
   else{
     printf("What is the contact's first name?\n"); 
     scanf("%s", &person.fname);
     printf("\nWhat is the contact's last name?\n");
     scanf("%s", &person.lname);
     printf("\nWhat is the contact's phone number?\n");
     scanf("%d", &person.pnumber);
   }
  break;     
 case 3:
  printf("\nName:%s\n%s \nNumber:%d \n",&person.fname,&person.lname,&person.pnumber);
  break;
 case 4:
  go = 1;
  break;
 default:
  printf("that wasn't an option. Please pick a valid option next time.\n");
 }

}
4

2 回答 2

4

您有一个简单的问题:C 语言使用“按值调用”,因此您的phonebook()函数会获取结构的副本。然后该phonebook()函数更改副本,但更改不会保存在任何地方。

你解决这个问题的方法:你必须让你的phonebook()函数接受一个指向结构的指针,然后它可以使用指针来修改结构。

int phonebook(struct contact *pcontact, int use)
{
    // ... stuff omitted ...

    printf("What is the contact's first name?\n");
    scanf("%s", pcontact->fname);  // "fname" works as a pointer

    printf("\nWhat is the contact's phone number?\n");
    scanf("%d", &pcontact->pnumber);  // must take address of integer "pnumber"

// ... rest of phonebook() omitted ...

// example of calling phonebook():
case 1:
    phonebook(&p1, choice);

http://www.lysator.liu.se/c/bwk-tutor.html#pointers

于 2013-07-17T20:18:13.827 回答
0

您是person按值传递,而不是按引用传递,因此phonebook对联系人结构的副本进行更改也是如此。

尝试

int phonebook(struct contact *person,int use);
于 2013-07-17T20:18:13.047 回答