2014-01-19 80 views
-2

如何使用結構作爲函數的參數?我嘗試這樣做:使用structura作爲函數的參數

struct 
{ 
    char name[30]; 
    char section[20]; 
    float grade; 
}student[30]; 

讀取和存儲信息的結構之後,我打電話將數據寫入到一個文件中的函數:

show(f,n,student); //n is the number of students 

這是展示功能:

void show(FILE *f,int n, struct elev); 
{ 
... 
} 

謝謝。

+0

看看http://stackoverflow.com/questions/13823886/c-passing-struct-as-argument –

+0

你真的應該花幾個小時閱讀一本好的C編程書籍。 –

回答

2

你會更好您的結構:

struct student_st { 
    char name[30]; 
    char section[20]; 
    float grade; 
}; 

既然你有幾個學生,你可能要一個指針傳遞給(陣列)其中:

void show(FILE *f,int n, struct student_st* s) { 
    assert (f != NULL); 
    assert (s != NULL); 
    for (int i=0; i<n; i++) { 
    fprintf(f, "name: %s; section: %s; grade: %f\n", 
      s->name, s->section, s->grade); 
    }; 
    fflush(f); 
} 

您將使用它:

#define NBSTUDENTS 30 
struct student_st studarr[NBSTUDENTS]; 
memset (studarr, 0, sizeof(studarr)); 
read_students (studarr, NBSTUDENTS); 
show (stdout, NBSTUDENTS, studarr); 

瞭解arrays are decaying into pointers