Define functions in structs

后端 未结 10 971
南旧
南旧 2020-12-08 08:58

Can we define functions in structs in C programming language?

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 09:56

    You can use only function pointers in C. Assign address of real function to that pointer after struct initialization, example:

    #include 
    #include 
    
    struct unit
    {
      int result;
      int (*add) (int x, int y);
    };
    
    int sumFunc(int x, int y) { return x + y; }
    
    void *unitInit()
    {
      struct unit *ptr = (struct unit*) malloc(sizeof(struct unit));
      ptr->add = &sumFunc;
      return ptr;
    }
    
    int main(int argc, char **argv)
    {
      struct unit *U = unitInit();
    
      U->result = U->add(5, 10);
    
      printf("Result is %i\n", U->result);
    
      free(U);
    
      return 0;
    }
    

    Good example of using function pointers in a struct you can find here https://github.com/AlexanderAgd/CLIST Check header and then clist.c file.

提交回复
热议问题