#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
int votes;
}
candidate;
void array_function(int arr[]);
int main(void)
{
candidate candidates[3];
candidates[0].votes = 5;
candidates[1].votes = 3;
candidates[2].votes= 1;
print_array_function(candidates.votes);
}
void print_array_function(int arr[])
{
for (int i = 0; i < 3; i++)
{
printf("%i\n", arr[i]);
}
}
I'm trying to run this code which declares a struct, feeds values into it and tries to pass an array inside the struct to a function. However, on doing so I get the following error:
test.c:22:30: error: member reference base type 'candidate [3]' is not a structure or union
array_function(candidates.votes);
How do I pass this structs array into the function?
Just declare the function like
void array_function( const candidate arr[], size_t n );
and call like
print_array_function( candidates, 3 );
The function can be defined the following way
void array_function( const candidate arr[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
printf( "%i\n", arr[i].votes );
}
}
Here, you have an array of structure candidate
which each element contains a single int
called votes
(certainly vote
would be a better name for it). Maybe the best approach to do what you want is to create a function print_candidate_array_vote
as:
void print_candidate_array_vote(candidate *candidates, unsigned int n_candidates)
{
for (int i = 0; i < n_candidates; i++) {
printf("%d\n", candidates[i].votes);
}
}
Try the code below, have made some changes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct candidate
{
int votes;
}
candidate;
void array_function(int arr[]);
int main(void)
{
candidate candidates[3];
candidates[0].votes = 5;
candidates[1].votes = 3;
candidates[2].votes= 1;
print_array_function(candidates);
}
void print_array_function(candidate arr[])
{
for (int i = 0; i < 3; i++)
{
printf("%i\n", arr[i]);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.