简体   繁体   English

在C中传递一个结构槽几个函数?

[英]Passing a struct trough several functions in C?

In my code I got a struct of this kind and two functions: 在我的代码中,我得到了这种结构和两个函数:

typedef struct {
    char team;
    int score;
} Player;

myfunc1 (Player *players) {
    players->score = 105;
    myfunc(?);
}

myfunc2(?) {
    //change again points and team character
}

And in main I create an array of that struct and pass it to a function: 在main中,我创建该结构的数组并将其传递给函数:

int main () {
    Player players[2]

    myfunc1(players)

}

I get to work the first function, but I don't know what argument I should pass from the first to the second to modify the array of players[2] created in main. 我开始使用第一个函数,但是我不知道我应该从第一个传递到第二个参数来修改main中创建的玩家数组[2]。

You can again use a simple pointer to access the data from players : 您可以再次使用一个简单的指针来访问players的数据:

void myfunc2 (Player *player)
{
    players->score = 123;
}

Call it from your myfunc1 like this: 像这样从myfunc1调用它:

myfunc2(players);

You will actually pass an address to Player structure stored in pointer Player* players (in function myfunc1 ) into local pointer variable Player *player in function myfunc2 . 你会真正传送的地址存储在指针球员结构Player* players (在功能myfunc1 )到本地指针变量Player *player在功能上myfunc2

To modify players[1] in your main function, call myfunc1 like this: 要在您的main功能中修改players [1],请像下面这样调用myfunc1

int main () {
    Player players[2]

    myfunc1(&players[1]); // & = give an address to your struct
}

Be careful about array indexes, they do start from zero, so if yu have an array with capacity of two ( Player players[2] ) then there are only two valid indexes: 0 an 1 . 注意数组索引,它们确实从零开始,因此,如果yu有一个容量为2的数组( Player players[2] ),则只有两个有效索引: 01 If you access indexes beyound the capacity your code will sooner or later crash. 如果您访问索引超出容量,则您的代码迟早会崩溃。

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

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