2
#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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Your struct *does not contain* an array. You can’t just treat the members of structs inside an array as an array of values. The error message says exactly that: `candidates` is of type *array* (more precisely, `candidate[3]`), it is *not* a struct type. – Konrad Rudolph Jul 30 '20 at 07:43

3 Answers3

0

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 );
    }
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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);
    }
}
Puck
  • 2,080
  • 4
  • 19
  • 30
0

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]);
   }
}
Riddhijain
  • 487
  • 2
  • 8