You must know the pointer base -7.void pointer to the function pointer

Source: Internet
Author: User
Tags define function types of functions

One, unable to move the "address"-void pointer 1.1 void pointer

void * denotes a " unknown type " pointer, and it is not known how many bytes from this pointer address begin with a single data. and using int to represent pointers, but more specifically "pointers".

So void* can only represent an address, cannot be used for & values, and cannot ++--move pointers , so it is not known how many bytes are a unit of data.

    intNums[] = {3,5,6,7,9}; void* PTR1 =Nums; //int i = *PTR1;//The void pointer cannot be directly evaluated    int* PTR2 = (int*) Nums; printf ("%d,%d\n", PTR1,PTR2); inti = *ptr2; printf ("%d\n", i);

As you can see from the output, the address is the same whether it is an untyped void pointer or an int type pointer:

PS:void * is an "address" that cannot be moved, and must be transformed into a type pointer before moving the pointer &.

1.2 The purpose of the void pointer

Here, let's take a look at the Memset function we learned earlier, whose first parameter is a void pointer, which can help us to block the differences of pointers of different types. As shown in the following code, we can either pass in a pointer to an array of type int or pass in a pointer to an array of type char:

    int nums[];    memset (nums,0,sizeof(nums));     Char chs[2];    memset (CHS,0,sizeof(CHS));

So, we can also try to do a self-simulation of this memset function, for the moment named Mymemset it:

voidMymemset (void*data,intNumintbytesize) {    //Char is a byte, and the computer is stored in bytes    Char*ptr = (Char*) data; inti;  for(i=0; i<bytesize;i++)    {        *ptr=num; PTR++; }}intMainintargcChar*argv[]) {    intnums[ -]; Mymemset (Nums,0,sizeof(nums)); inti,len=sizeof(nums)/sizeof(int);  for(i=0; i<len;i++) {printf ("%d", Nums[i]); } printf ("\ n"); return 0;}

In this mymemset function, we use the void pointer to receive different types of pointers, use the char type (one byte) to read each byte of memory byte by bit, and then fill in the specified number in turn. Since the char type is a concrete type, you can use + + or--to move the pointer.

For struct types, we can also use our Mymemset function:

struct _person{    Char *name;     int Age ;} person; Person P1;mymemset (&p1,0,sizeof);p rintf ("p1. age:%d\n", p1.age);

The results of the final run are as follows:

the use of void *: When you only know the memory, but don't know what type it is.

Second, the function pointer 2.1 pointer to the function-. The prototype of a delegate in net

I'd like to use it. NET, for the function pointer should not be unfamiliar, it is the prototype of the delegate. The function pointer is a pointer to a function, and we can easily define a function pointer in C:

void (*intfunc) (int i);

Here we define a function pointer IntFunc with no return value, only one int type argument. We can use this function pointer in the main function to point to a specific function (this specific function definition needs to be consistent with the definition of the function pointer):

    // declaring a function pointer    of type IntFunc IntFunc f1 = test1;     // executes the code area    that the F1 function pointer points to F1 (8);

Here the Test1 function is defined as follows:

void test1 (int  age) {    printf ("test1:%d\n", Age);}

As shown in the final run result, executing the function pointer F1 executes the specific function it points to:

2.2 Basic use of function pointers

Here we use a small case to do a basic introduction to the function pointer. I believe that most of C # or Java yards are familiar with foreach, so we're going to simulate the different processing of foreach values in an int array. The code that is specific to the for loop is reused, but how the data is handled is not deterministic, so the logic that handles the data is specified by the function pointer.

 void  foreachnums (int  *nums,int   Len,intfunc func) { int   I;  for  (I=0 ; i<len;i++ int  num = Nums[i];    Func (num); }}  void  printnum (int   num) {printf (  value=%d\n   " ,num);}  

In the Foreachnums function, we define a intfunc function pointer, and the Printnum function is a specific function that satisfies the INTFUNC definition. Here we pass the Printnum function as a function pointer to the FOREACHNUMS function in the main function.

    int 1,5,666,23423,223  };    Foreachnums (nums,sizeof(nums)/sizeof(int), printnum);

The results of the final run are as follows:

Through the function pointers, we can block the different kinds of specific processing methods, that is, the uncertainty of the factors are dependent on the abstraction, which is the essence of abstract or interface-oriented programming.

Third, the function pointer application Case 3.1 calculates the maximum value of any type-getmax

(1) Define function pointers and Getmax bodies:

typedefint(*comparefunc) (void*data1,void*data2);//Getmax function Parameter description://the first address of data array to be compared, number of bytes of unitesize cell//Length: The size of the data. {1,3,5,6}:length=4//Compare the data that data1 and Data2 point to,//returns a positive number if DATA1>DATA2void*getmax (void*data,intUnitSize,intlength,comparefunc func) {    inti; Char*ptr = (Char*) data; Char*max =ptr;  for(i=1; i<length;i++)    {        Char*item = ptr+i*unitsize; //How to take a few bytes to compare is inside the func thing        if(func (Item,max) >0) {Max=item; }    }    returnMax;}

Here you can see, in the Getmax in the end to take a few bytes to compare is by the comparefunc point of the function to do, getmax do not care at all.

(2) define different types of functions that conform to the definition of a function pointer:

intIntdatacompare (void*data1,void*data2) {    int*PTR1 = (int*) data1; int*PTR2 = (int*) data2; inti1=*ptr1; inti2=*ptr2; returnI1-I2;} typedefstruct_dog{Char*name; intAge ;} Dog;intDogdatacompare (void*data1,void*data2) {Dog*dog1 = (dog*) data1; Dog*DOG2 = (dog*) data2; return(dog1->age)-(dog2->Age );}

(3) Call in the main function for the int type and struct type:

intMainintargcChar*argv[]) {    //Test1:int type to find the maximum value    intNums[] = {3,5,8,7,6 }; int*pmax = (int*) Getmax (nums,sizeof(int),sizeof(nums)/sizeof(int), intdatacompare); intMax = *PMax; printf ("%d\n", Max); //test2: Maximum value for struct typeDog dogs[] ={{"Shar",3},{"Sausage",Ten},{"Husky",5},        {"BEIJING-Pakistan",8},{"Big Dog",2}}; Dog*pdog = (Dog *) Getmax (dogs,sizeof(Dog),sizeof(dogs)/sizeof(Dog), dogdatacompare); printf ("%s=%d",pdog->name,pdog->Age ); return 0;}

The results of the final run are as follows:

Qsort function in 3.2 C-custom sort

Qsort is included in the <stdlib.h> header file, which is sorted quickly by The comparison criteria you give , and by pointer movement. The result of sorting is still placed in the original array. Use the Qsort function to write a comparison function yourself . We can look at the prototype of the Qsort function:

void Qsort (void * base, size_t num, size_t size, int (* comparator) (const void *, const void *));

As you can see, the fourth parameter of Qsort is a function pointer! The function it points to should be a return value of type int, with a parameter of two void pointers. Well, we can use the two compare methods we've written above as parameters to pass in the qsort to quickly sort the arrays of int and struct.

    intNums[] = {3,5,8,7,6 }; Qsort (Nums,sizeof(nums)/sizeof(int),sizeof(int), intdatacompare); inti;  for(i=0;i<sizeof(nums)/sizeof(int); i++) {printf ("%d", Nums[i]); } printf ("\ n"); Dog dogs[]={{"Shar",3},{"Sausage",Ten},{"Husky",5},        {"BEIJING-Pakistan",8},{"Big Dog",2}}; Qsort (Dogs,sizeof(dogs)/sizeof(Dog),sizeof(Dog), dogdatacompare);  for(i=0;i<sizeof(dogs)/sizeof(DOG); i++) {printf ("%s%d", Dogs[i].name,dogs[i].age); }

So, is there a result after a quick sort? The answer is yes, we can pass in various comparison methods, can be sorted in ascending order or in descending order.

Resources

such as Peng Network, "C language can also do big Things (third edition)"

Zhou Xurong

Source: http://edisonchou.cnblogs.com

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

You must know the pointer base -7.void pointer to the function pointer

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.