简体   繁体   中英

Passing array of struct to a function

I'm trying to pass data of a struct between the main and another function (on a different file .c) with no success. I have a struct like this

struct player{
    char name[10];
    int budget;
};

typedef struct player Player; 

void PrintFunc(Player p); //function prototype

Player gamer[2] = {{"Alice", 100},
                   {"Bob", 100 }};

And I call it from the main func with something like

PrintFunc(gamer);

The function structure should be something like this

void PrintFunc(Player p){
//stuff
}

What am I doing wrong?

gamer is an array, PrintFunc expects a single object.

Option 1:

PrintFunc(gamer[0]);
PrintFunc(gamer[1]);

Option 2: change the function to accept a pointer to Player objects:

void PrintFunc(Player *p, size_t len){
    for(size_t i = 0; i < len; ++i)
        // do something with p[i]
}

int main(void)
{
    Player gamer[2] = {{"Alice", 100},
                   {"Bob", 100 }};

    PrintFunc(gamer, sizeof gamer / sizeof *gamer);
    return 0;
}
void PrintFunc(Player p[]){ 
    //stuff 
}

Receive array of player objects when sending array of player objects

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.

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