Initialize Static Array of Structs in C

后端 未结 3 1611
暗喜
暗喜 2021-02-03 20:34

I\'m implementing a card game in C. There are lots of types of cards and each has a bunch of information, including some actions that will need to be individually scripted assoc

相关标签:
3条回答
  • 2021-02-03 20:41

    Your approach is exactly right.

    1. This will work, and is a good way to avoid huge switch statements.
    2. You can't define functions inline in C, they each must have a unique name.
    3. extern is what you want, not static. Change your body to be this:

      struct CARD cardDefinitions[] = { 
          {0, 1, do_card0}, 
          {1, 3, do_card1} 
      }; 
      

      then in an appropriate header file:

      extern struct CARD cardDefinitions[];
      
    0 讨论(0)
  • 2021-02-03 20:47

    Your approach is right and will work. Your function pointer syntax is right, except that you don't use parameter names - just types:

    int (*do_actions)(struct GAME_STATE *, int, int);
    
    0 讨论(0)
  • 2021-02-03 20:48
    1. That should work fine. It seems like you'd have a lot of functions if you're doing one per card, but maybe this particular game requires that level of control

    2. You can't define them inline, but you can just do a forward declaration. You need to do &func_name in the struct initialization though

    3. No; extern means a variable is declared in another file, so it doesn't make sense to have an extern variable that you're declaring at that location. Also, static means the variable is only accessible from the current file, which is the opposite of what you want. Making it read-only would require a getter function, but if you just want to make it accessible from another file declare it normally here (struct cardDefinitions[] = {...}) and in the other file use an extern (extern struct cardDefinitions[];)

    0 讨论(0)
提交回复
热议问题