我正在尝试编写一个函数,该函数将初始化数组中N个结构的所有值。我选择使用void函数并使用结构指针。使用单一结构指针没有问题,但是我无法弄清楚如何将指针地址传递给函数的结构数组。
以下代码产生一个错误。
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
有人对如何修复我的语法有更好的建议吗?
之所以会出错,是因为您有一个指向数组的指针,并将其视为内部的指针数组Initialize
。
在您的情况下,您可以简单地传递一个简单的指针:
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;
}
}
来自main的呼叫将变为:
Initialize(fp, candidates, electionCandidates); //save candidate names and set votes = to 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句