[英]Passing Array of Structs to a Function as a Pointer (C)
我正在尝试编写一个函数,该函数将初始化数组中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
有人对如何修正我的语法有更好的建议吗?
传递数组使用指向其中第一项的指针,该指针已经是数组名称。 首先从以下位置更改函数声明:
void Initialize(FILE *fp, int candidates, election *electionCandidates[]);
至
void Initialize(FILE *fp, int candidates, election *electionCandidates);
并这样称呼它:
Initialize(fp, candidates, electionCandidates);
另一件事是您访问数组中的结构项的成员,因为它是指针数组。 使用.
运算符。
那是您应该使它起作用的方法。 现在,我将告诉您您做了什么:
election *electionCandidates[]
是一个指向election
类型的指针 &electionCandidates
是指向election
类型指针的地址 并且在函数主体中, electionCandidates
是指向数组而不是数组的指针,这就是为什么如果要访问数组的元素,应该调用类似以下内容的原因:
(*electionCandidates)[eN].name
之所以出错,是因为您有一个指向数组的指针,并将其视为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
这行:
election electionCandidates[candidates];
是election
结构类型的数组。 对于数组,您不需要像现在那样通过引用显式传递:
Initialize(fp, candidates, &electionCandidates);
只要这样做:
Initialize(fp, candidates, electionCandidates);
在C中,数组是通过引用自动传递的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.