C Pointers && functions

Source: Internet
Author: User

First, the function pointer


As the name implies, a function pointer, first it is a pointer, because it can point to a function, so called a function pointer. Can be likened to array pointers.


Similar to defining an array pointer, a function pointer is defined as follows:

function return value type (* variable name) (function parameter type)

such as Void (*pfun) (int) //function pointer pfun The type of function pointed to is void (int)

To determine what the following code means.



(1), char * (*FUN1) (char * p1, char * p2);

(2), char * *fun2 (char * p1, char * p2);

(3), char * FUN3 (char * p1, char * p2);


As long as the above code is considered as a priority, we can easily judge it.

Solution:

(1), * First combined with fun1, so fun1 is a pointer, remove (*FUN1), is fun1 can point to the type, so fun1 is a function pointer. The type of function you can point to is char* (char* p1,char* p2). So the (1) Line statement defines a function pointer.

(2), () priority is higher than * so fun2 first with (), so fun2 is a function, the function of the return value type is char**, the number of arguments is (CHAR*P1,CHAR*P2), so this is a function of the declaration.

(3), same as (2) Fun3 is a function, which is a declaration of one by one functions.


So what's the use of a function pointer? A function pointer, like a normal pointer, can be accessed to a pointed object as a reference. You can invoke a function by dereferencing the function pointer.

# include <stdio.h>int add (int a,int b) {return a+b;}        int main () {int (*padd) (Int,int) =&add;//defines the function pointer padd points to add () int ret=0;    Ret=add (2,3);        Ret= (*padd) (2,3);        printf ("%d\n", ret); return 0;}



Second, array of function pointers


As the name implies, an array of function pointers is first an array, because the array element is a function pointer, so called an array of function pointers.


1. Definition of function pointer array


How do you define an array of function pointers?

Let's take a look at how normal arrays and pointer arrays are defined.

Char arr1[3]; Character array

Char *arr2[3]; Array of pointers


Similarly, char (*arr[3]) (char*); Array of function pointers

In fact, it is good to understand that [] precedence is higher than *,arr first with [3], so arr is an array, size 3; remove arr[3], which is the type of the array element, char (*) (char*) This is a function pointer type. So arr is a function pointer array size of 3.


2. Initialization of arrays


Just like initializing an ordinary array, the element of the array is the address of the function.

For example, an array element is a pointer to an int (Int,int) class function

Int (*pfun[3]) (int,int) ={fun1,fun2,fun3}; You can also {&FUN1,&FUN2,&FUN3}


3. Application of function pointer Array (simple calculator implementation)

#include  <stdio.h>int add (int a,int b) {    return a+b;} Int sub (int a,int b) {    return a-b;} Int mul (int a,int b) {    return a*b;} Int div (int a,int b) {    return a/b;} Int main () {    int input=1;    int x=0,y=0;     int ret=0;    int (*p[4]) (int,int) ={add,sub,mul,div};     while (input)     {        printf ("1.add   2.sub  3.mul  4.div  0.exit\n ");        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%d", &input);         if (input>0&&input<5)         {             printf ("Please enter the operand \ n");       &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%d%d", &x,&y);             ret= (*p[intput-1]) (x, y);             printf ("%d\n", ret);        }         else if (input==0)              break;        else             printf ("Input error, please re-enter \ n");             }    return 0;}

The above code uses a function pointer array to implement the calculator, without a function pointer array can also use the switch statement, but if the function of the calculator is complex to use a large number of case statements, in such cases, using a function pointer array can reduce code redundancy.



Array pointers for array of function pointers


As the name implies, an array pointer to an array of function pointers, first it is a pointer, because it points to an array, so it is called an array pointer, and this array is a function pointer array, so this pointer is an array pointer to the array of function pointers.


The following is an array pointer that defines a simple array of function pointers:

char * (* (*parr) [3]) (char * p);

* First with Parr, so Parr is a pointer, remove (*PARR) is Parr can point to the type,

char* (*[3]) (CHAR*P): * First with [3], this is an array of pointers, Parr point to an array, remove [3] is the type of the array, char* (*) (CHAR*P) This is a function pointer type, so Parr is a pointer to the array of function pointers array.


Simply take an address to an array of function pointers, and the addresses you remove can be initialized or assigned to pointers to the array of function pointers.



Four, callback function


1. Concept


What is a callback function?

A callback function is a function that is called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function.


Now that a function can be called through a function pointer, is it possible to encapsulate a function that can add and subtract and implement multiplication? The answer is yes. (This is not true in the function's internal judgment)

callback function #include <stdio.h>int add (int a, int b) {    return  a+b;} Int sub (int a, int b) {    return a-b;} Int mul (int a, int b) {    return a*b;} Int div (int a, int b) {    return a/b;} Int op (int  (*pfun) (int , int))   //callback function op, just give the function the address of the above function,                                 //can achieve a two-digit subtraction {    return pfun (for a);} Int main () {    int input=1;    int x=0,y=0;     int ret=0;    int (*p[4]) (int,int) ={add,sub,mul,div};     while (Input) &NBSP;&NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; printf ("1.add  2.sub  3.mul  4.div  0.exit\n");   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%d", &input);         if (input>0&&input<5)          {            printf (" Please enter the operand \ n "); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%d%d ", &x,&y) ;             ret= op (p[input-1]);             printf ("%d\n", ret);         }        else if (input==0)              break;         else            printf ("Input error, please re-enter \ n");             }    return 0;}

In fact, the above example does not need to use a callback function to implement, this is too complex, and too overqualified, but the understanding.


2. Application


Now let's take a look at the application of the callback function

Write a bubble sort function to sort strings, sort numbers, and sort characters.

#include  <stdio.h> #include  <string.h>int com_int (const void *elem1,  const void *elem2 ) {    return * (int *) elem1 - * (int  *) elem2;} Int com_str (const void *elem1, const void *elem2) {    return &NBSP;STRCMP ((char *) * (int *) elem1,  (char *) * (int *) elem2);} Int com_char (CONST&NBSP;VOID&NBSP;*ELEM1,&NBSP;CONST&NBSP;VOID&NBSP;*ELEM2) {     return* (char*) elem1 - * (char*) elem2;} Void swap (Char *p1, char *p2, size_t sz) {    size_t i  = 0;    for (i = 0; i<sz; i++)     { char tmp = * (P1+i); * (P1+i)  = * (p2+i); * (P2+i)  = tmp;     }}void bubble_sort (void *base, size_t num, size_t width,int (*CMP) (CONST&NBSP;VOID&NBSP;*ELEM1,&NBSP;CONST&NBSP;VOID&NBSP;*ELEM2)) {    size_t  i = 0,j=0;    for (i = 0;  i < num-1; i++)     {         for (j = 0; j < num-1-i; j++) {    if (CMP (char  *) base+ width*j,  (char *) base+width* (j+1))  > 0)     {                 swap ((char *) base+ width*j,  (char *) base+width* (j+1),  width);    }}     }}int main () {    //char *arr1[] = {"bbbb", "AAAA", "dddd", " CCCC "};    //int arr1[] = { 1, 3, 5, 7, 2, 4,  6, 8 };    char arr1[] =  "ASDGGT";    int i = 0,len=0;         len = sizeof (arr1)  / sizeof (arr1[0]);         bubble_sort (Arr1,len , sizeof (char),  com_char);         for (i = 0 ;i<sizeof (arr1)/sizeof (arr1[0]); i++)     {         printf ("%c\n", Arr1[i]);    }     printf ("\ n");         return 0;}









This article is from the "Newli" blog, make sure to keep this source http://15129279495.blog.51cto.com/10845420/1737892

C Pointers && functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.