我试图写将初始化在数组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