C ++ (1) - a function pointer

Compared with the function pointer function call, only the parameter description (description of the internal function is) without arguments passed. Like arrays, the function pointer is the function name. In the following figure, c ++ qsort built-in functions (implemented sorting) the function pointer is required:

Here Insert Picture Description

MyCompare qsort function pointer function is a function call rule: if the elements 2 before the element 1, the return value is negative.
Important:
Incoming parameters of type const void * (pointer), because as a void, does not know its point size of elements (size is qsort required argument)
Taking into account the elements of an array are unsigned int type, so use p1, p2 will elem1, elem2 cast to unsigned int * type (i.e., corresponding to the data type of pointer), then use * p1, * p2 refers elem1, elem2 points to be compared elements
here though finished cast but pay attention to point to elements is unchanged

------ therefore take this one down, because the direct use * elem1 is illegal, by the compiler is not
then written note array:
unsigned int AN [NUM] = {1,2,3,4,5} ;

#include<iostream>
int max(int a,int b){return a>b?a:b;};

int main(){
int (*ptr)(int,int);
ptr = max;//将函数首地址赋值给函数指针
int a=1,b=2,c;
c = (*ptr)(a,b);//传入实参
return 0;}
Released eight original articles · won praise 1 · views 128

Guess you like

Origin blog.csdn.net/wouldlikemathpix/article/details/104363827