c语言中函数指针用法,C语言函数指针的用法
這篇文章簡單的敘述一下函數指針在結構體中的應用,為后面的一系列文章打下基礎
引言
指針是C語言的重要組成部分, 于是深入理解指針并且高效地使用指針可以使程序員寫出更加老練的程序。我們要記住指針是一個指向內存地址的變量。指針可以引用如int、char……常見的數據類型,例如:
int * intptr; // 聲明一個指向整型值的指針
int intval = 5 ; // 定義一個整型變量
intptr = & intval ; // intptr現在包含intval的地址
指針不僅僅指向常規的類型還可以指向函數
函數指針
函數指針的內容不難理解,不再贅述,參見《C語言函數指針的用法》
語法
要聲明一個函數指針,使用下面的語法:
Return Type??(*function pointer's variable name?)?(?parameters?)
例如聲明一個名為func的函數指針,接收兩個整型參數并且返回一個整型值
int (*func)(int a , int b ) ;
可以方便的使用類型定義運用于函數指針:
typedef int (*func)(int a , int b ) ;
結構體中的函數指針
我們首先定義一個名為Operation的函數指針:
typedef int (*Operation)(int a , int b );
再定義一個簡單的名為STR的結構體
typedef struct _str {
int result ; // 用來存儲結果
Operation opt; // 函數指針
} STR;
現在來定義兩個函數:Add和Multi:
//a和b相加
int Add (int a, int b){
return a + b ;
}
//a和b相乘
int Multi (int a, int b){
return a * b ;
}
現在我們可以寫main函數,并且將函數指針指向正確的函數:
int main (int argc , char **argv){
STR str_obj;
str_obj.opt = Add; //函數指針變量指向Add函數
str_obj. result = str_obj.opt(5,3);
printf (" the result is %d\n", str_obj.result );
str_obj.opt= Multi; //函數指針變量指向Multi函數
str_obj. result = str_obj.opt(5,3);
printf (" the result is %d\n", str_obj.result );
return 0 ;
}
運行結果如下:
the result is 8
the result is 15
完整的代碼如下:
#include
typedef int (*Operation)(int a, int b);
typedef struct _str {
int result ; // to sotre the resut
Operation opt; // funtion pointer
} STR;
//a和b相加
int Add (int a, int b){
return a + b ;
}
//a和b相乘
int Multi (int a, int b){
return a * b ;
}
int main (int argc , char **argv){
STR str_obj;
str_obj.opt = Add; //函數指針變量指向Add函數
str_obj. result = str_obj.opt(5,3);
printf ("the result is %d\n", str_obj.result );
str_obj.opt= Multi; //函數指針變量指向Multi函數
str_obj. result = str_obj.opt(5,3);
printf ("the result is %d\n", str_obj.result );
return 0 ;
}
來源:https://www.cnblogs.com/wuyudong/p/function-pointer-in-c-struct.html
總結
以上是生活随笔為你收集整理的c语言中函数指针用法,C语言函数指针的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小子注入,怎么使用呢?
- 下一篇: 工业自动化控制软件SCADA数据模型的使