I am attempting to write a function that will initialize all values of N structs in an array. I chose to use a void function and use a structure pointer. I have no issue with using single structure pointers, but I cannot figure out how to pass a pointer address to an array of structs to my function.
The following code produces a single error.
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;
}
}
The error I have points to this line:
Initialize(fp, candidates, &electionCandidates); //save candidate names and set votes = to 0
Does anyone have advice on how to fix my syntax, or a better way to go about this?
You get an error because you have a pointer to an array and you treat it as an array of pointers inside Initialize
.
In your case you can simply pass a simple pointer:
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;
}
}
The call from main will become:
Initialize(fp, candidates, electionCandidates); //save candidate names and set votes = to 0
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다