Ad

Passing An Array From A Struct As An Argument To A Function

- 1 answer

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

Ad

Answer

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 );
    }
}
Ad
source: stackoverflow.com
Ad