在C中初始化结构的静态数组

rus*_*l_h 33 c arrays static struct

我在C中实现了一个纸牌游戏.有很多类型的卡片,每个都有一堆信息,包括一些需要单独编写脚本的动作.

给定这样的结构(我不确定我的函数指针是否正确)

struct CARD {
    int value;
    int cost;
    // This is a pointer to a function that carries out actions unique
    // to this card
    int (*do_actions) (struct GAME_STATE *state, int choice1, int choice2);
};
Run Code Online (Sandbox Code Playgroud)

我想初始化一个静态数组,每个卡一个.我猜这看起来像这样

int do_card0(struct GAME_STATE *state, int choice1, int choice2)
{
    // Operate on state here
}

int do_card1(struct GAME_STATE *state, int choice1, int choice2)
{
    // Operate on state here
}

extern static struct cardDefinitions[] = {
    {0, 1, do_card0},
    {1, 3, do_card1}
};
Run Code Online (Sandbox Code Playgroud)
  1. 这是否有效,我是否正确地采用这种方式?我试图避免大量的switch语句.

  2. 我是否需要提前定义'do_cardN'函数,或者是否有某种方法可以在结构的初始化中内联定义它们(类似于python中的lambda函数)?

  3. 我需要从另一个文件中对cardDefinitions进行只读访问 - 'extern static'是否正确?

我知道这是很多问题,但我对如何解决这个问题真的有些模糊.

谢谢.

编辑:

要清楚,我的目标是能够做类似的事情

int cost = cardDefinitions[cardNumber].cost;
Run Code Online (Sandbox Code Playgroud)

要么

int result = cardDefinitions[cardNumber].do_action(state, choice1, choice2);
Run Code Online (Sandbox Code Playgroud)

而不是在所有地方使用巨大的开关语句.

Gre*_*ill 40

你的方法是完全正确的.

  1. 这将起作用,并且是避免大量switch陈述的好方法.
  2. 您无法在C中内联定义函数,它们每个都必须具有唯一的名称.
  3. extern是你想要的,而不是static.改变你的身体:

    struct CARD cardDefinitions[] = { 
        {0, 1, do_card0}, 
        {1, 3, do_card1} 
    }; 
    
    Run Code Online (Sandbox Code Playgroud)

    然后在适当的头文件中:

    extern struct CARD cardDefinitions[];
    
    Run Code Online (Sandbox Code Playgroud)

  • 你实际上可以在C中使用"内联"函数.你要找的是"匿名函数".此外,我将{0,0,NULL}添加为数组的最后一个元素,因此您无需单独存储其大小. (3认同)