简体   繁体   English

如何从函数传递结构和int并返回给main? C

[英]How can I pass a struct and an int from an function and back to main? C

I am trying to return back the array persons and the quantity_persons_count to main() but I cant get it to work. 我试图将数组person和quantity_persons_count返回到main(),但是我无法使其工作。 I have tried changing void to int and person but that obv doesnt work. 我试图将void更改为int和person,但是该obv无效。

struct person{..}
int main(){
 int o;
 int quantity_persons_count = 0;
 struct person persons[100];

 while(1){

    printf("1.Add a new person");
    scanf("%i",&o);

    switch(o)
    {
        case 1: AddPerson(persons,quantity_persons_count);
                break;
}

void AddPerson(struct person *persons, int quantity_persons_count){
 if(quantity_persons_count == 100){
    printf("ERROR.\n");
 }
 else{
     printf("name\n");
     scanf("%s",persons[quantity_persons_count+1].name);
     quantity_persons_count++;
     printf("done\n");

}

}

If you want changes to quantity_persons_count to be visible in main , you need to pass a pointer to it: 如果你想改变quantity_persons_count是在可见的main ,你需要一个指针传递给它:

void AddPerson(struct person *persons, int *quantity_persons_count){

     if(*quantity_persons_count == 100){
        printf("ERROR.\n");
     }
     else{
         printf("name\n");
         scanf("%s",persons[*quantity_persons_count+1].name);
         (*quantity_persons_count)++;
         printf("done\n");

    }

}

Then you call it like this: 然后,您可以这样称呼它:

AddPerson(persons,&quantity_persons_count);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM