anon anon - 3 months ago 10
C Question

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. I have tried changing void to int and person but that obv doesnt work.

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");

}

}

Answer

If you want changes to quantity_persons_count to be visible in main, you need to pass a pointer to it:

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