c - 通过 C 中的几个函数传递结构?

标签 c struct

在我的代码中,我得到了一个这种结构和两个函数:

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

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

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

在 main 中,我创建了一个该结构的数组并将其传递给一个函数:

int main () {
    Player players[2]

    myfunc1(players)

}

我开始使用第一个函数,但我不知道应该从第一个函数传递什么参数到第二个函数来修改在 main 中创建的玩家 [2] 数组。

最佳答案

您可以再次使用一个简单的指针来访问来自播放器的数据:

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

像这样从你的 myfunc1 调用它:

myfunc2(players);

您实际上会将地址传递给存储在指针 Player* players 中的 Player 结构(在函数 myfunc1 中)到局部指针变量 Player *player 在函数 myfunc2 中。

要在 main 函数中修改 players[1],请像这样调用 myfunc1:

int main () {
    Player players[2]

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

注意数组索引,它们确实从零开始,所以如果你有一个容量为 2 的数组 (Player players[2]),那么只有两个有效索引: 01。如果您访问超出容量的索引,您的代码迟早会崩溃。

关于c - 通过 C 中的几个函数传递结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20174177/

相关文章:

c - 访问 zip 文件

c - 循环递增并保持状态

c - 交换 2 个字节的整数

c - 如何链接 ELF 文件中的数据以在运行时显示? STM32

c++ - 如何从未排序的链表中删除重复项

c - Mac OS X 中的 makefile 缺少分隔符

c - 初始化包含数组的结构

ios - 使用特定关键字从结构填充 UITableView

c++ - 结构与对象 C++

c - 如何在C中动态添加结构成员?