简体   繁体   English

将结构中的数组作为参数传递给 function

[英]Passing an array from a struct as an argument to a function

#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.我正在尝试运行此代码,该代码声明一个结构,将值输入其中并尝试将结构内的数组传递给 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?如何将此结构数组传递到 function?

Just declare the function like只需像这样声明 function

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 function 可以通过以下方式定义

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).在这里,您有一个结构candidate数组,其中每个元素都包含一个名为votesint (当然, vote是一个更好的名称)。 Maybe the best approach to do what you want is to create a function print_candidate_array_vote as:也许做你想做的最好的方法是创建一个 function print_candidate_array_vote为:

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]);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM