天天看點

C語言結構體數組執行個體

今天我看到一個項目中關于結構體數組函數是這麼用的,總結出來

結構體數組 + 結構體成員是函數指針;

可以根據需求自己判斷,并調用相應的函數,實作想要的功能。

比如:根據不同的名字的判斷,去告訴我想要對每個人說的話。

#include <stdio.h>

//函數聲明
int zhao_f(char *subject, int time);
int zhou_f(char *subject, int time);

//定義一個函數指針類型
typedef int (*learn)(char *subject,int time);

//定義一個結構體類型,成員是函數指針類型
typedef struct student{
    learn learning;
}student;

//定義結構體數組。調用不同的函數,實作不同的功能
student stu[] = {
    {zhao_f},
    {zhou_f}
};


//定義實作函數1,(函數指針類型)
int zhao_f(char *subject, int time)
{
    printf("Misszhao learn %s %d\n", subject, time);
    return 0;
}

//定義實作函數2
int zhou_f(char *subject, int time)
{
    printf("Misszhou learn %s %d\n", subject, time);
    return 0;
}

//定義test調用函數,,
learn test(int num)
{
    return stu[num].learning;
}

//根據不同的需求,調用不同的函數去實作
void test1()
{
//可以分支去實作你的功能
    learn learn_test;
    learn_test = test(0);
    learn_test("chinese", 10);

    learn_test = test(1);
    learn_test("math", 5);
}
int main(int argc, char *argv[]){
    test1();   
    return 0;
}
           

bao:day0823 bao$ gcc -o test1 test1.c

bao:day0823 bao$ ./test1

Misszhao learn chinese 10

Misszhou learn math 5

int num-----主要就是根據需求(也可以是char *),去達到調用不同函數 的功能。

zhou_f和zhao兩個是具體的功能實作函數;

stu------是一個數組,他的每個數組成員都是一個結構體student,

結構體student隻有一個成員,是一個函數指針類型learn

繼續閱讀