我試圖寫將初始化在數組n結構的所有值的函數。我選擇使用void函數並使用結構指針。我有使用單一結構的指針沒有問題,但我無法弄清楚如何將指針地址傳遞給結構的陣列,以我的功能。傳遞結構的數組的函數作爲指針(C)
下面的代碼產生單一錯誤。
typedef struct candidate {
char name[20]; //name of the election candidate
int votes; //amount of votes the candidate has
} election;
void Initialize(FILE *fp, int candidates, election *electionCandidates[]);
int main(void)
{
const int candidates = 7; //this will be the amount of structs initialized
const int voters = 365; //this will be the N iterations of a for loop for the voting process
FILE *fp = fopen ("elections.txt", "R"); //save file pointer for use when taking formatted input
election electionCandidates[candidates]; //declare 'candidates' structs, one for each candidate in the election
Initialize(fp, candidates, &electionCandidates); //save candidate names and set votes = to 0
fclose(fp);
return 0;
}
void Initialize(FILE *fp, int candidates, election *electionCandidates[]) //init values of the candidate struct array by passing pointer to void function
{
int eN = 0, N = candidates; //eN = executed number of for loop iterations, N = total number of iterations to be completed
for (eN = 0; eN < N; eN ++)
{
char name[20] = "";
fscanf (fp, "%s", &name);
strcpy(electionCandidates[eN]->name, name);
electionCandidates[eN]->votes = 0;
}
}
我有指向該行的錯誤:
Initialize(fp, candidates, &electionCandidates); //save candidate names and set votes = to 0
有沒有人對如何解決我的語法,或者更好的辦法去了解這個建議嗎?
將'char name [20] =「」;'改爲'char * name = malloc(20)'和'fscanf(fp,「%s」,&name);'''fscanf(fp,「%s」, &name)'也是一個好主意,請把它包含在你的答案中 – Igor 2014-09-05 13:36:37
謝謝!這個編譯和應該工作,還沒有用一個輸入文件測試它看起來像我複雜它拋出所有的指針語法我記得不知道什麼時候可以使用它,需要刷一下:B – River 2014-09-05 13:41:03