2016-08-20 57 views
-1

我想返回數組人員和quantity_persons_count到main(),但我不能讓它工作。我曾嘗試將void更改爲int和person,但該obv不起作用。如何從函數傳遞一個struct和一個int並返回到main? C

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

} 

} 
+1

不知道聲明,'scanf(「%s」,&persons [quantity_persons_count + 1] .name);'似乎通過傳遞錯誤類型的數據來調用*未定義的行爲。如果'persons [quantity_persons_count + 1] .name'是一個'char'數組,'&'應該被移除。 – MikeCAT

+0

什麼是數組返回?你如何從'main()'調用這個函數,你如何測試它?請考慮發佈[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – MikeCAT

+0

您可能想知道的是[參數按值傳遞](http://stackoverflow.com/documentation/c/1006/function-parameters/10900/parameters-are-passed-by-value#t=20160820014330354564) 。 – MikeCAT

回答

2

如果你想改變quantity_persons_countmain是可見的,你需要一個指針傳遞給它:

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

    } 

} 

然後調用它像這樣:

AddPerson(persons,&quantity_persons_count); 
+0

我收到錯誤:'AddPerson'衝突類型 – anon

+1

@anon您需要更改函數原型以符合定義。 – dbush

+0

謝謝你們! – anon

相關問題