C Language Learning Notes (vii) function pointers

Source: Internet
Author: User

"Function pointers" and "pointer functions" are a pair of concepts that can easily stun people, but it is not difficult to grasp the attributive. These two nouns are abbreviations, the pointer function is a function that returns a value as a pointer , and the function pointer is a pointer to a function . This article mainly speaks about function pointers.

We have an int pointer, a char pointer, which is a pointer to the actual address of the variable. In the C language, when compiling functions, each function has an entry address, which is called a function pointer when we point to the entry address with a pointer. With such a pointer, you can call the function by accessing the pointer. From this point of view, the function pointer is actually the same as the basic type pointer definition, except that it points to a different object. So, let's look at the different function pointers.


Novice field: A simple pointer to a function

int add (int a, int b) {return a+b;} int sub (int a, int b) {return a-A;}    int main (int argc, char** argv) {int (*p) (int, int) =null;    p = add;        Prtint (P (2,3));    Output 5 p = sub;        Prtint (P (3,1)); Output 2 return 0;}

Description: The above prtint is an output macro, which is actually the printf function, just to facilitate observation of the use of pointers. As you can see, the function pointer is defined by the return type (* pointer name) ([parameter list]). Attention:

    • The type and parameters of the function pointer and the return value of the pointing function must be strictly consistent ;

    • You can also write int (*p) (int a, int b) in the form of a pointer. The naming of formal parameters has no effect;

    • Giving pointers to the form of assigning values can also be written P = &add; There is no essential difference between the two ways.

    • The form of a call pointer can also be written (*p) (2,3).


Advanced fields: Complex function pointers

* (int*) &p----What is this?

Take a look at this piece of code:

void Fun () {printf ("call fun () \ n");}    int main (int argc, char** argv) {void (*p) ();      * (int*) &p = (int) &fun;    The effect is equivalent to P = fun; (*p)    (); return 0;}

Although the note has been "spoiler", but the first time to see * (int *) &p = (int) &fun; A friend of this expression would probably have a headache. Deal with this complex expression, do not worry, a little bit to chew, will always understand.

First look at the right side of the equals sign. As mentioned earlier, the function name itself can actually represent an address, and &fun is also the address. Then (int) &fun means to convert this address to int type.

Take a look at the previous expression: void (*p) (); This is a simple function pointer. Represents a function pointer (actually a fun style) with a return value of void and a null argument list.

The &p represents the address of the pointer variable p itself, which is a 32-bit constant (under 32bit system).

(int *) &p means that the address to which it is taken is coerced into a pointer of type int.

then * (int *) &p = (int) &fun; is to assign the address of this fun () function to p. So actually the effect of this line of code is equivalent to P = fun;.

As can be seen from this example, the function pointer is also a pointer, nothing special at all, the general pointer can do the operation it can do.


(* (Void (*) ()) 0) (); What is this?

This is a classic example of "C pitfalls and pitfalls". Here's a look at what this code means:

First step: void (*) (). This can be seen as a function pointer, the return value of this function is void, and the argument list is empty. Note that this pointer does not have a name, perhaps the most confusing place.

Step Two: (Void (*) ()) 0. This is to cast 0 into this type of pointer. 0 is an address, which means that the starting address of the function is assumed to be at 0 points.

Step Three: (* (Void (*) ()) 0) (). You can see that this step is just one more (*) () than the previous step. Therefore, this is a function call.

Although layer-by-layer can finally see the true face of this line of code, but in fact this code is not directly executed, if you do not believe you can put in the main function to try. I think this should be due to the reason of the 0 address. We can test it completely and use the following code:

void Fun () {printf ("call fun () \ n");}    int main (int argc, char** argv) {(* (void (*) ()) 0x401352) ();//Void (*p) () = fun;//(*p) (); return 0;}

I'm using Codeblocks, first using the code in the comment, and looking at the actual address value of the function in the Watch window, I'm 0x401352. Then replace the above code in 0 to this address, the latter two sentences off, the results show that the call to fun ().

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/4D/E6/wKiom1RcOwugdBewAABc8pFioMo276.jpg "title=" Qq20141107112203.jpg "alt=" Wkiom1rcowugdbewaabc8pfiomo276.jpg "/>

There are more complex function pointer forms, not listed here, but as long as you keep in mind the method is not afraid: first find the core most like the simple function pointer of the part, and then a little bit of unfolding slowly analysis. This is like Sun Monkey's eyes, let your goblin How to change vest, always be I see flaw, is not?


Array of function pointers

Now we can see through the vest of the function pointer, for example, here is a function pointer:

char * (*PF) (char *p);

Considering the concept of arrays, it is possible to put together elements of the same type to form an array. So we put the function pointer in an array is not the following:

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

This...... There are many stars ... Well, it's an array of length 3. Each element of an array is a function pointer. Each function pointer points to a function that returns a value type of char*, and the formal parameter list has only one char* parameter. Here, this is straightened out, and most importantly it is an array. The following code demonstrates the use of this array:

char * FUN1 (char *p) {printf ("%s\n", p); return p;}    char * FUN2 (char *p) {printf ("%s\n", p); return p;}    int main (int argc, char **argv) {char* (*pa[2]) (char*);    Pa[0] = fun1;    Can be used directly with the function name pa[1] = &fun2;    can also add & symbol Pa[0] ("fun1");    Pa[1] ("fun2"); return 0;}


Pointer to array of function pointers

This is more of a mouthful. However, as soon as we understand the array of function pointers, the pointers to the array of function pointers are not incomprehensible. Pointers to function pointers are no different than other pointers, except that the difficulty of debugging may increase. The following code defines a pointer to an array of function pointers, interested students can see, here will not repeat.

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

This article is from the "Flying Cat" blog, be sure to keep this source http://flyingcat2013.blog.51cto.com/7061638/1573976

C Language Learning Notes (vii) function pointers

Related Article

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.