C语言结构体中如何包含函数

 

#include <stdio.h>
#include <malloc.h>

struct Hello{
    void (*sayHello)(char* name);
};

void sayHello(char* name){
    printf("hello, %s\n",name);
}

int main(){
    struct Hello* hello=(struct Hello *)malloc(sizeof(struct Hello));
    hello->sayHello=sayHello;//这个结构体有多少个函数,就要在这个有多少个结构体内,函数指针指向函数的声明。
    hello->sayHello("a");
    free(hello);

    return 0;
}

 

posted @ 2020-12-28 12:04  ziwuxian  阅读(1936)  评论(0编辑  收藏  举报