You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中为struct结构体添加函数类型成员

问题解答

C语言本身不支持直接在结构体中定义普通函数,但可以通过函数指针作为结构体成员实现类似效果,你的实现思路是正确的,仅赋值语法存在错误。

错误原因

  • 你代码中*a.func = *testfunction();存在两处逻辑问题:
    1. testfunction()带括号会直接执行函数而非获取函数地址,你的函数返回值为void,无法用来给指针赋值
    2. 函数名本身就代表函数的入口地址,不需要额外加解引用符*,给函数指针成员赋值时直接使用函数名即可

修正后的可运行代码

#include<stdio.h>

typedef struct{
    void (*func)(void);
}test;

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

int main()
{
    test a;
    // 正确赋值写法:直接将函数名赋值给函数指针成员
    a.func = testfunction;
    a.func();
    return 0;
}

扩展常用写法

实际使用中通常会给函数指针增加一个结构体自身指针的参数,方便操作结构体内部的其他成员,效果类似C++的this指针:

#include<stdio.h>

typedef struct test{
    int num;
    // 第一个参数为结构体自身指针
    void (*print_num)(struct test* self);
}test;

void test_print(test* self){
    printf("结构体中的num值为:%d\n", self->num);
}

int main(){
    test a;
    a.num = 1024;
    a.print_num = test_print;
    // 调用时把自身地址传进去即可操作结构体内部成员
    a.print_num(&a);
    return 0;
}

内容的提问来源于stack exchange,提问作者Pear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:36:03