C 结构体 结构体指针 指针函数 学习记录

#include<stdio.h>
struct data{
    int x;
    int y;
};
struct data1{
    int x;
    int y;
}p1,p2;
typedef struct{
    int x;
    int y;
}data3;

//函数指针,指向函数
int(*func)(int a, int b);
int bar(int a, int b)
{
    return a + b;
}
int foo(int a, int b)
{
    return a;
}

//结构体中含有指针函数
struct hello_driver {
int(*test)(struct data *);
};
int hello(struct data *h){
    return h->x;
}

//含有指针函数的结构体直接初始化
struct hello_driver driver2={
    .test=hello,
};
void main(){
    struct data hello1;
    hello1.x=10;
    printf("hello world %d\n",hello1.x);
    p1.x = 20;
    printf("hello world %d\n",p1.x);
    data3 p2;
    p2.x =30;
    printf("hello world %d\n",p2.x);
    //函数指针指向bar函数
    func=bar;
   //调用函数指针
    printf("hello world %d\n",func(1,2));
    func=foo;
    printf("hello world %d\n",func(5,6)); 
   //含有函数指针的结构体
    struct hello_driver driver;
    driver.test=hello;
    struct data *h;
    h=&hello1;
    printf("hello world %d\n",driver.test(h));
    printf("hello world %d\n",driver2.test(&hello1));
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章