Skip to content

Instantly share code, notes, and snippets.

@JackYang-hellobobo
Created January 17, 2024 19:35
Show Gist options
  • Save JackYang-hellobobo/98956a2f11eef4b4e07df206938554de to your computer and use it in GitHub Desktop.
Save JackYang-hellobobo/98956a2f11eef4b4e07df206938554de to your computer and use it in GitHub Desktop.
C 语言 函数指针 回调函数

C语言 函数指针 回调函数

#include<stdio.h>

int max(int a,int b){
    return a>b?a:b;
}

int main(void){
    int a,b;
    scanf("%d %d",&a,&b);
    int (*ptr)(int,int)=&max;//函数指针本身来说就是调用函数
    int c=ptr(a,b);
    printf("%d",c);
    return 0;
}

详解回调函数

以下是来自知乎作者常溪玲的解说:你到一个商店买东西,刚好你要的东西没有货,于是你在店员那里留下了你的电话,过了几天店里有货了,店员就打了你的电话,然后你接到电话后就到店里去取了货。在这个例子里,你的电话号码就叫回调函数,你把电话留给店员就叫登记回调函数,店里后来有货了叫做触发了回调关联的事件,店员给你打电话叫做调用回调函数,你到店里去取货叫做响应回调事件。

  1. 电话号码 : 回调函数
  2. 给店员 : 登记回调函数
  3. 到货了 :触发回调关联事件
  4. 店员打电话给我 : 调用回调函数
  5. 我到店取货 :响应回调事件
#include <stdlib.h>  
#include <stdio.h>
 
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
    for (size_t i=0; i<arraySize; i++)
        array[i] = getNextValue();
}
 
// 获取随机值
int getNextRandomValue(void)
{
    return rand();
}
 
int main(void)
{
    int myarray[10];
    /* getNextRandomValue 不能加括号,否则无法编译,因为加上括号之后相当于传入此参数时传入了 int , 而不是函数指针*/
    // 这个其实做了一个函数指针的替换操作 int (*getNextValue)(void)= &getNextRandomValue
    populate_array(myarray, 10, getNextRandomValue);
    for(int i = 0; i < 10; i++) {
        printf("%d ", myarray[i]);
    }
    printf("\n");
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment