C語言複習第五章:函數指針

希望寫一篇來把函數指針的內容回顧一下

  1. 函數的指針的兩種定義方法及三種使用方法

int myfun(int a,char b)
{
    printf("int myfunc\n");
    return 0;
}

int test01()
{
    //函數指針寫法一
    typedef int(TYPE_FUN)(int,char);
    TYPE_FUN *f = myfun;
    //三種用法
    f(10,'a');
    (*f)(20,'b');
    myfun(30,'c');

    //函數指針寫法二
    int (*f2)(int,char) = NULL;
    f2 = myfun;
    f2(40,'d');
}
  1. 函數指針數組的使用方法

int fun01()
{
    printf("fun01()");
}

int fun02()
{
    printf("fun02()");
}

int fun03()
{
    printf("fun03()");
}
//函數指針數組
int test02()
{
    int i;
    int (*fun_array[3])();
    /* 換成void類型void value not ignored as it ought to be*/
    fun_array[0] = fun01();
    fun_array[1] = fun02();
    fun_array[2] = fun03();

    for(i = 0;i < 3;i++)
    {
        fun_array[i]();
    }

    return 0;
}
  1. 函數指針做參數 打印數組元素
//函數指針做參數 回調函數
void printfall(void *a,int elsesize,int size,void(*print)(void *))
{
    char *a1 = (char*)a;
    int i ;
    for(i = 0;i < size;i++)
    {
        printf("%d\n",a + i*elsesize);//與原數組地址做對比
        print(a + i*elsesize);//調用myprint函數,打印出數組元素
    }
}

void myprintf(void *a)
{
    int *a2 = (int *)a;
    printf("%d\n",*a2);
}

void test03()
{
    int i;
    int a[] = {1,2,3,4,5};
    printfall(a,sizeof(int),sizeof(a)/sizeof(int),myprintf);
/* 打印數組各元素地址
    printf("--------------------\n");

    for(i = 0;i < 5;i++)
    {
        printf("%d\n",&a[i]);
    }
*/
}
  1. 做參數,打印出結構體數組元素

typedef struct person
{
    char name[64];
    int age;
}person;

void printfalls(void *a,int elsesize,int size,void(*print)(void *))
{
    char *a1 = (char*)a;
    int i;
    for(i = 0;i < size;i++)
    {
        char *pers = a1+i*elsesize;
        print(pers);
    }
}


void myprintfs(void*per)
{
    person *p = (person*)per;
    printf("name:%s,age:%d\n",p->name,p->age);
}

void test04()
{
    int i;
    person per[] =
    {
        {"aaa",64},
        {"bbb",65},
        {"ccc",66},
    };
/*
    for(i = 0;i < 3;i++)
    {
        printf("%d\n",&per[i]);
    }
*/
    printfalls(per,sizeof(person),sizeof(per)/sizeof(person),myprintfs);

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