1. 程式人生 > 其它 >DC-2

DC-2

函式指標的應用場景+typedef

https://blog.csdn.net/weixin_47921628/article/details/117688224     https://zhuanlan.zhihu.com/p/372557271

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct Student {
    int id;
    char name[100];
    int score;
}Student;
//列印輸出排序後的結構體
void print(Student a[], int
len) { for (int i = 0; i < len; i++) { printf("%d %s %d\t", a[i].id,a[i].name ,a[i].score ); printf("\n"); } } //結構體傳參無腦傳指標 typedef int(*Stu)(Student* x, Student* y); void bubbleSort(Student a[], int len,Stu stu) { for (int bound = 0; bound < len; bound++) { for
(int cur = len - 1; cur > bound; cur--) { // 因為函式指標指向的函式的形參是指標,故實際呼叫的實參為:&變數名 if (stu(&a[cur - 1], &a[cur]) == 1) { Student temp = a[cur - 1]; a[cur - 1] = a[cur]; a[cur] = temp; } } } } //按照id排列設定回撥函式
int idDesc(Student* a, Student* b) { //降序 return a->id < b->id ? 1 : 0; } int idAsce(Student* a, Student* b) { //升序 return a->id > b->id ? 1 : 0; } //按照分數設定回撥函式 int scoreDesc(Student* a, Student* b) { return a->score < b->score ? 1 : 0; } int scoreAscec(Student* a, Student* b) { return a->score > b->score ? 1 : 0; } //按照成績升序排,如果成績相同按照id 升序排 int scorAsce_idAsce(Student* a, Student* b) { if (a->score == b->score) { return a->id > b->id ? 1 : 0; } return a->score > b->score ? 1 : 0; } int main() { Student arr[] = { {1,"張三",78}, {3,"王五",89}, {4,"趙六",97}, {2,"李四",78} }; int len = sizeof(arr) / sizeof(arr[0]); bubbleSort(arr, len, scorAsce_idAsce); print(arr, len); bubbleSort(arr, len,idAsce); print(arr, len); system("pause"); return 0; }
View Code

typedef void(*Func)(void)為什麼能這麼用?:相當於定義了一種型別,這個型別具有下面的特徵:他是一個函式,沒有返回值,沒有引數。

所以它還能夠 

 

//構造3個通用函式
void TEST1(void) { printf("test1\n"); }//函式定義  
void TEST2(void) { printf("test2\n"); }//函式定義  
void TEST3(void) { printf("test3\n"); }//函式定義  
... ...  
//宣告  
typdef void (*func)(void);

void test(int i)  
{  
  func vTask[3] = {&TEST1, &TEST2, &TEST3};  
  func fun = vTask[i];  
  (*fun)();  
}  
View Code