What is a function pointer?

(This article is an excerpt from the CSDN forum report, only for learning, if there is any infringement, please contact to delete)

We know that when ordinary variables are defined, the compiler will automatically allocate a suitable memory. The same is true for functions. When compiling, a function is compiled and then placed in a block of memory.

(The above statement is actually very inaccurate, because the compiler will not allocate memory, and the compiled code is also placed on the disk in binary form, and will be loaded into the memory only when the program starts running)

If we store the first address of the function in a pointer variable, we can call the pointed function through this pointer variable. This special pointer that stores the first address of the function is called a function pointer .

For example, there is a function  int func(int a);

How do we declare a function pointer that can point to func?

int (*func_p)(int);

It seems a bit strange. In fact, the declaration format of the function pointer variable is the same as the declaration of the function func, except that func is replaced by (*func_p).

Why do we need parentheses? Because if you don't need parentheses,  int *func_p(int);  is to declare a function that returns a pointer. The parentheses are to avoid this ambiguity .

Let's look at a few more function pointer declarations:

int (*f1)(int); // 传入int,返回int 
void (*f2)(char*); //传入char指针,没有返回值 
double* (*f3)(int, int); //传递两个整数,返回 double指针

Let's look at the specific use of a function pointer:

# include <stdio.h>

typedef void (*work)() Work; // typedef 定义一种函数指针类型

void xiaobei_work() {
 printf("小北工作就是写代码");
}

void shuaibei_work() {
 printf("帅北工作就是摸鱼")
}

void do_work(Work worker) {
  worker();
}
int main(void)
{
  Work x_work = xiaobei_work;
  Work s_work = shuaibei_work;
  do_work(x_work);
  do_work(s_work);
  return 0;
}

Output:

小北工作就是写代码

帅北工作就是摸鱼

In fact, it is a bit used here for the purpose of using function pointers, but everyone should realize that the biggest advantage of function pointers is to make functions variable .

We can pass functions as parameters to other functions, so we have the prototype of polymorphism. We can pass different functions to achieve different behaviors.


void qsort(void* base, size_t num, size_t width, int(*compare)(const void*,const void*))

This is the declaration of the qsort function in the C standard library  . Its last parameter requires a function pointer to be passed in. This function pointer is responsible for comparing two elements.

Because the method of comparing two elements is only known to the caller, we need to tell qsort in the form of a function pointer how to determine the size of the two elements.

 

Well, the function pointer is briefly introduced here.

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_38915078/article/details/112391201