当前位置:网站首页>[C language] pointer function, function pointer and array function
[C language] pointer function, function pointer and array function
2022-06-10 13:50:00 【A egg of maker Association】
Table of contents title
Pointer function and function pointer are often confused in development .
Pointer function
Format : type * Function name ()
return Same value as function type ;
The body of a pointer function is a function , The type returned is pointer .
Is to point the pointer to the value returned by this function .
int* f(int x,int y);
// Because parentheses have a high priority
// So it is first and foremost a possession x,y A function of two variables , Then one more int The pointer of type points to it .
The main body :f(int x,int y)
Functions can return numeric values , For normal functions, it should be like this :
int f(int x,int y)
{
x=1;
return x;
}
// here f() The return is x, The data type is int type
Using a pointer function is like this ( Incorrect usage ):
int* f(int x,int y)
{
x=1;
return x;
}
// here f() The return is x The value of the address , amount to (int *)x;
This must be the wrong data , Because the pointer points to the past 1(x Value ) In the address of
The correct usage should be to point to with a pointer x The address you are in can be correct x To operate :
int* f(int x,int y)
{
x=1;
return &x;
}
// here f() The return is x Value , amount to (int *)&x
(int *)&x == x;
Small turtle pointer function analysis
The following is the code of the little turtle pointer function :
One of them is to use the characteristics of pointer function : amount to char *(return “xxx”), A string can be used as a pointer , If not * Equivalent to char (return “xxx”), Only one character type is returned , added * Is equivalent to taking "xxx" The first address , The return is from xxx The value in the address .
Do not return a local variable of a function :
Note the scope of the local variable , Local variables can return addresses , But the data may no longer exist
A function pointer
Format : type (* Pointer name ) ( Parameters of the function to point to )
The body of a function pointer is a pointer , Is used to point to a function .
This pointer is used to point to a large area where this function is located .( The function name is the first address of the function )
int (*f) (int x,int y);
// Because parentheses have a high priority .
// So it is first of all a int (*f) The pointer to , Then point to the parameter (x,y) Function of .
The main body :int (*f)
Use function pointers as arguments

int calc(int (*fp)(int,int),int num1,int num2);
calc(sub,3,5) The first parameter of : That is, use the function pointer to point to sub Address of function .
Start with the call , (*fp) This pointer is already sub Function .
namely (*fp)(int,int) == sub(int,int)
Data is from return (*fp)(num1,num2) Coming out , amount to sub(num1,num2)
Function pointer advanced
#include<stdio.h>
int add(int, int);
int sub(int, int);
int cal(int (*)(int, int), int, int);
int (*select(char a))(int, int);
int add(int num1, int num2)
{
return num1 + num2;
}
int sub(int num1, int num2)
{
return num1 - num2;
}
int cal(int (*fp)(int, int), int num1, int num2)
{
return (*fp)(num1,num2);
}
int (*select(char op))(int num1, int num2)
{
switch(op)
{
case '+':return add;
case '-':return sub;
}
}
int main()
{
int num1, num2;
char op;
//int (*fp)(int, int);
printf("please enter a formular\n");
scanf("%d %c %d", &num1, &op, &num2);
printf("%d\n", cal(select(op), num1, num2));
return 0;
}
Pay attention to cal A function is a function with three arguments , The first parameter is a function pointer .
select A function is a pointer function , Its return value is a function pointer .
When the input “1+2” The flow of this program is as follows . First “+” This symbol is read into op In this parameter , then op This parameter is passed in select function ,select Function switch Statement discovery op Is a plus sign , So it returns a point to add Function pointer to function , This function pointer is used as cal Function parameters are dereferenced after being passed in , And then num1 and num2 Pass in add Function to get the return value 3.
int (*select(char op))(int num1, int num2)
// It can be understood as : type (* A function pointer )( Parameters 1, Parameters 2)
call printf("%d\n", cal(select(op), num1, num2)); When ,
cal Can be called with function pointer select,select According to the passed parameters op,
To choose which function to return add Or function sub The first address .
The first address is finally transferred to int cal(int (*fp)(int, int), int num1, int num2) in ,
By cat Function pointer of (int (*fp) To dereference .
amount to (int (*fp)(return add)= function add(num1,num2);
“ Array function ”( Digression )
stay c The concept of fishing array function in the language , But we can write array functions artificially ( No define)
Format : int (* Array )( The parameters of the function );
int (* arr[8])(int a);
Array function cases :
#include <stdio.h>
#include <stdlib.h>
#define EPSINON 0.000001 // Define the allowable error
double add(double x, double y);
double sub(double x, double y);
double mul(double x, double y);
double divi(double x, double y);
double add(double x, double y)
{
return x + y;
}
double sub(double x, double y)
{
return x - y;
}
double mul(double x, double y)
{
return x * y;
}
double divi(double x, double y)
{
// Do not... On floating point numbers == or != Compare , because IEEE Floating point numbers are an approximation
if (y >= -EPSINON && y <= EPSINON)
{
printf(" The divisor cannot be zero 0\n");
// If the divisor is 0, call exit() Function to exit the program directly
exit(1);
}
else
{
return x / y;
}
}
int main(void)
{
int i;
double x, y, result;
double (*func_table[4])(double, double) = {
add, sub, mul, divi};// The first address of the function is stored in the array , Use a function pointer to point to this address to reference this function To form a function array
printf(" Please enter two numbers :");
scanf("%lf %lf", &x, &y);
printf(" The result of adding, subtracting, multiplying and dividing these two numbers is :");
for (i = 0; i < 4; i++)
{
result = (*func_table[i])(x, y);
printf("%.2f ", result);
}
putchar('\n');
return 0;
}
double (*func_table[4])(double, double) = {add, sub, mul, divi};
Is an array function , There are four function names ( First address ).
call (*func_table[i])(x, y) It's called [i] The function corresponding to the name .
amount to :
(*func_table[1])(x, y)==(add(x, y));
(*func_table[2])(x, y)==(sub(x, y));
(*func_table[3])(x, y)==(mul(x, y));
(*func_table[4])(x, y)==(divi(x, y));
General high-level languages have these ,C The language is less used ( But not without ).
A little , Write again when you have time , Relatively complex .
边栏推荐
- New features mail GPU counter module adds GPU primitive processing and GPU shader cycles
- How to locate the hot problem of the game
- Record common functions in MySQL at work
- 【无标题】音频蓝牙语音芯片,WT2605C-32N实时录音上传技术方案介绍
- buuctf [PHP]CVE-2019-11043
- Leetcode-57- insert interval
- 五角大楼首次承认资助46个乌生物设施 俄方曾曝只有3个安全
- 常识,神经元数量,小鼠的脑内神经元大约在7000万个、人类约有860亿个
- WT2003H4-16S 语音芯片按键录音及播放应用解析
- [Huang ah code] I cleaned the console of Google browser in this way
猜你喜欢

Im instant messaging development: the underlying principle of process killed and app skills to deal with killed

【操作教程】如何正确使用海康demo工具配置通道上线?

Qt: 访问其他窗体中的控件

WT2003H4-16S 语音芯片按键录音及播放应用解析
![buuctf [PHP]XDebug RCE](/img/e2/bcae10e2051b7e9dce918bf87fdc05.png)
buuctf [PHP]XDebug RCE

解决跨海高并发崩溃难题?so easy

如何定位游戏发热问题

Flutter drawer学习总结6
![Buuctf [glassfish] arbitrary file reading](/img/37/e3c127f2f2ba97c5ca0b6cf01cf9ab.png)
Buuctf [glassfish] arbitrary file reading

Solve the problem of cross sea high concurrent crash? so easy
随机推荐
【操作教程】如何正确使用海康demo工具配置通道上线?
New features mail GPU counter module adds GPU primitive processing and GPU shader cycles
Leetcode-57- insert interval
软件智能:aaas系统 度量衡及文法的形式规则
传奇登录器提示连接服务器失败是怎么回事?怎么解决?
Application analysis of key recording and playing of wt2003h4-16s voice chip
组装芯片难保竞争优势,痛定思痛的高通终于开始自研核心架构
How to deal with the interview for the fresh senior graduates who want to self-study software testing?
Recyclerview multi layout writing method, "my" and "personal center" page classic writing method demonstration
Can qiniu open an account? Can the security of securities companies be directly opened on the app
Qt: 访问其他窗体中的控件
Markdown Title centered
Flutter Listview, Column, Row学习个人总结2
What are the common automated test frameworks? Shanghai software testing company Amway
Libre circulation des ressources dans le cloud et localement
[FAQ] résumé des problèmes courants et des solutions lors de l'utilisation de l'interface API rest du Service de santé sportive
《软件体系结构原理、方法与实践》第二版期末考试复习总结
[Huang ah code] I cleaned the console of Google browser in this way
Implementation of VGA protocol based on FPGA
[Huang ah code] teacher, I want to choose software development related majors after the college entrance examination. Which direction do you think is better? How to fill in the college entrance examin