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));
}

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