【问题标题】:How to add functions to members of struct in c [duplicate]如何在c中向struct的成员添加函数[重复]
【发布时间】:2021-12-23 21:13:00
【问题描述】:

我需要在 c 中的结构成员中包含一个函数。我该怎么做?

我研究了一下,但没有找到任何东西。我对 c 有点陌生,不太了解它的用途。

#include<stdio.h>

//so i have a struct like this
typedef struct{
    void (*func)(void);
}test;

void testfunction(void){
    printf("Hello World!\n");
}

//as far as i have searched -> i have come up to this

int main()
{
    test a;
    *a.func = *testfunction();
    //this doesn't work
    a.func();
}

我认为这应该是可能的,但我不知道该怎么做。任何帮助表示赞赏。

【问题讨论】:

  • *放在两边就行了:a.func = testfunction;
  • @Gerhardh 是的,David 也提到了

标签: c struct function-pointers


【解决方案1】:

void *func; 不是指向函数的有效指针,代码中的 cmets:

#include<stdio.h>

typedef struct{
    void (*func)(void); // Don't forget to include the arguments
}test;

void testfunction(void){
    printf("Hello World!\n");
}

int main()
{
    test a;
    a.func = testfunction; // Without parentheses / Without dereferencing
    a.func();
}

【讨论】:

  • @DavidRanieri 你是个救命稻草 :) 这是一小段大代码
猜你喜欢
  • 2019-08-28
  • 2012-03-08
  • 2012-04-20
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
  • 2018-07-30
  • 2021-10-30
  • 1970-01-01
相关资源
最近更新 更多