zoukankan      html  css  js  c++  java
  • 函数指针

    1、基本概念

    程序运行期间,每个函数都会占用一段连续的内存空间。而函数名就是该函数所占

    内存区域的起始地址(也称“入口地址”)。我们可以将函数的入口地址赋给一个指针变

    量,使该指针变量指向该函数。然后通过指针变量就可以调用这个函数。这种指向函数

    的指针变量称为“函数指针”。

    2、指针变量的定义形式

    返回值类型名  (* 指针变量名)(参数1类型, 参数2类型, ...);
    

    3、使用方法

    可以用一个原型匹配的函数的名字给一个函数指针赋值。要通过函数指针调用它所指向

    的函数,写法为:

    函数指针名(实参表);
    

     如下示例:

    #include <stdio.h>
    #include <stdlib.h>
    
    int add(int a, int b)
    {
        return a+b;
    }
    
    int main()
    {
    
        int (*pf)(int, int);
        pf = add;
        printf("%d
    ", pf(3, 8));
        
        return 0;
    }

    4、函数指针有什么作用?

    至少让我们知道函数库中的 qsort 怎么用~

    man 手册页中对qsort有如下说明

    #include <stdlib.h>
    
    void qsort(void *base, size_t nmemb, size_t size,
                    int (*compar)(const void *, const void *));

    The  qsort()  function sorts an array with nmemb elements of size size.
    The base argument points to the start of the array.

    The contents of the array are sorted in ascending order according to  a
    comparison  function  pointed  to  by  compar, which is called with two
    arguments that point to the objects being compared.

    The comparison function must return an integer less than, equal to,  or
    greater  than  zero  if  the first argument is considered to be respec‐
    tively less than, equal to, or greater than the second.  If two members
    compare as equal, their order in the sorted array is undefined.

    这里

    
    
    int (*compar)(const void *, const void *)
    
    

    就是一个函数指针的定义,实际上只要我们传入一个满足其函数原型的函数名即可。

    举例如下:

    #include <stdio.h>
    #include <stdlib.h>
    
    int compare(const void * a, const void *b)
    {
        return *(int *)a - *(int *)b;
    }
    
    int main()
    {
        int a[4] = {23, 5, 9, 2};
        qsort(a, 4, sizeof(int), compare);
    
        int i = 0;
        for (i = 0; i < 4; i++)
        {
            printf("%d
    ", a[i]);
        }
        
        return 0;
    }
  • 相关阅读:
    Github开始强制使用PAT(Personal Access Token)了
    STM32F401的外部中断EXTI
    STM32F401的PWM输出
    STM32F103和STM32F401的ADC多通道采集DMA输出
    nRF24L01无线模块笔记
    51单片机(STC89C52)在Ubuntu下的开发
    51单片机(STC89C52)的中断和定时器
    51单片机的软件和硬件PCA/PWM输出
    Zadig 云原生持续交付 面向开发者设计的开源、高可用 CI/CD
    人生 乐观 悲观 英雄
  • 原文地址:https://www.cnblogs.com/aqing1987/p/4181132.html
Copyright © 2011-2022 走看看