C语言结构体内部的函数指针有什么意义

Python012

C语言结构体内部的函数指针有什么意义,第1张

//在结构体中包含函数指针

//这样,可以使用结构体,调用函数。

//这个有点像C++的面向对象的类 

//十分好用。 

#include "stdio.h"  

struct DEMO  

{  

    int x,y  

    int (*func)(int,int) //函数指针  

}  

int add2(int x,int y)  

{  

    return x+y  

}  

int main()  

{

int ret=0

    struct DEMO demo  

    demo.func=&add2 //结构体函数指针赋值  

    ret=demo.func(3,4)

    printf("func(3,4)=%d\n",ret)  

}

指针就是指向内存的某个地址的一个变量。

结构体指针就是这个指针变量的值必须指向存放该结构体的内存位置。

当这个指针没有任何指向时,可以赋值为null值,但是改指针不可使用,程序中应该做判断。下面是一些赋值演示。

struct student{

int id

int score

} aaa

struct student *p = null//结构体指针p初始化赋值为null

struct student *p2=&aaa//p2指向aaa

struct student *p3=(struct student *)malloc(sizeof(struct student))//内存中申请一个结构体空间,并将地址强制转换为结构体指针变量赋值给p3