函数指针与指针函数区别

Posted aron566

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了函数指针与指针函数区别相关的知识,希望对你有一定的参考价值。

简述

最近看到安森美芯片的boot的部分代码,如下,写的不易观看,可能C萌新,不易理解,这涉及到指针函数,函数指针的相关概念。

typedef enum
{
    BOOTROM_ERR_NONE = 0x0,
    BOOTROM_ERR_BAD_ALIGN = 0x1,
    BOOTROM_ERR_BAD_SP = 0x2,
    BOOTROM_ERR_BAD_RESET_VECT = 0x3,
    BOOTROM_ERR_FAILED_START_APP = 0x6,
    BOOTROM_ERR_BAD_CRC = 0x7
} BootROMStatus;

#define ROMVECT_BOOTROM_START_APP 0x00000030
/* ----------------------------------------------------------------------------
 * Function      : BootROMStatus Sys_BootROM_StartApp(uint32_t* vect_table)
 * ----------------------------------------------------------------------------
 * Description   : Validate and start up an application using the Boot ROM.
 * Inputs        : vect_table   - Pointer to the vector table at the start of an
 *                                application that will be validated and then
 *                                run.
 * Outputs       : return value - Status code indicating application validation
 *                                error if application cannot be started. If not
 *                                returning, the status code is written to the
 *                                top of the started application's stack to
 *                                capture non-fatal validation issues.
 * Assumptions   : None
 * ------------------------------------------------------------------------- */
__STATIC_INLINE BootROMStatus Sys_BootROM_StartApp(uint32_t* vect_table)
{
    return (*((BootROMStatus (**)(uint32_t*))
              ROMVECT_BOOTROM_START_APP))(vect_table);
}

测试代码

在线C编程网站,测试如下代码,http://www.dooccn.com/c/

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

typedef uint8_t (**pFunc)(uint32_t*);//函数指针
typedef uint8_t (*pFunc1)(uint32_t*);//函数指针
typedef uint8_t *(*pFunc2)(uint32_t*);//指针函数 返回值是指针

static uint8_t test(uint32_t *par)
{
    printf("test.\\r\\n");
    return 0;
}

static uint8_t test1(uint32_t *par)
{
    printf("test1.\\r\\n");
    return 1;
}

static uint8_t *test2(uint32_t *par)
{
    printf("test2.\\r\\n");
    return NULL;
}
pFunc1 fun_array[2] = 
{
  [0] = test,
  [1] = test1,
};

pFunc1 t0 = test;
pFunc1 t1 = test1;
pFunc2 t2 = test2;
pFunc t = &fun_array[0];

int main(void) { 

    (*(t))(NULL);
    (*((uint8_t (**)(uint32_t*))t))(NULL);
	return 0;
}

运行结果

test.
test.

以上是关于函数指针与指针函数区别的主要内容,如果未能解决你的问题,请参考以下文章

指针函数与函数指针的用法与区别

指针函数与函数指针的用法与区别

结构体指针与结构体变量用作函数参数时有啥区别,在用法上

指针函数与函数指针的区别

指针函数与函数指针的区别

指针函数与函数指针的区别