C語言中的函數指針定義

#include <stdio.h>

int max(int x, int y)
{
    return (x >= y ? x : y);
}

typedef int (*FUNC_PTR)();

int main(int argc, char *argv[])
{
    int      arr[5] = {1, 2, 3, 4, 5};
    FUNC_PTR func   = NULL;
    
    /* 函數調用 */
    func = max;
    printf("max(2, 3)=%d \n", func(2, 3));
	
	return 0;
}

上面的代碼沒有問題,但是,如果將函數指針定義修改爲 typedef int (*FUNC_PTR)(void);  則會編譯失敗。

[Warning] ...\Projects\test\main.c:16: warning: assignment from incompatible pointer type
[Error] ...\Projects\test\main.c:17: error: too many arguments to function


這說明定義函數指針時,(*FUNC_PTR)()並不等同於 (*FUNC_PTR)(void); 

另外,可以給(*FUNC_PTR)()定義的函數傳遞參數。






發佈了28 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章