Defining function pointers in structs

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/unix21/article/details/9293877

The definition of a

struct pointer variable defines the general form of a struct variable as follows:

Form 1: First define struct type, then define variable
struct struct identifier
{
member variable list;
};
struct Body identifier * pointer variable name;

Variable initialization one: struct struct identifier variable name ={Initialize value 1, initialize value 2, ..., initialize value n};


Form 2: Define the variable
struct struct identifier
{
member variable list at the same time that the type is defined; ....
} * pointer variable name;

Variable initialization two:


Form 3: Define variables directly, define variables directly in the nameless struct only once
struct
 {
member variable list;
}* pointer variable name;


where pointer variable name is the name of the struct pointer variable. Form 1 defines a struct and then defines a struct pointer variable of this type, and Form 2 and form 3 are defined as struct pointer variables of this type at the same time as the struct body is defined.


function pointer definition

General function pointers can be defined as:

Int (*func) (int,int);
The
represents a pointer to any function that contains two int parameters and returns a value of int. If there is a function such as:

int add2 (int x,int y)

{

return x+y;

}

This can be done when the pointer func is actually used:

func=&add2;//pointer assignment, or FUNC=ADD2; ADD2 is the same as &ADD2

printf ( Func (3,4) =%d\n ", func (3,4));

In fact, for porting of code, it is common to use TypeDef to define function pointer types.

typedef int (*fun) (int,int);

Fun func=&add2;

Func ();



struct contains function pointer

in a struct, you can also include a function pointer variable like a generic variable. The following is a simple implementation.

#include <stdio.h>structdemo{intx, y;int(*func) (int,int);//function Pointers};intADD1 (intXinty) {returnx*y;}intADD2 (intXinty) {returnx+y;}voidMain () {structDEMO Demo;demo.func=ADD2;//struct function pointer assignment//demo.func=&add2;//struct function pointer assignmentprintf"func (3,4) =%d\n", Demo.func (3,4));d Emo.func=add1;printf ("func (3,4) =%d\n", Demo.func (3,4));}/*Output: func (3,4) =7func (3,4) =12*/

#include"stdio.h"structdemo{intx, y; int(*func) (int,int);//function Pointers};intADD2 (intXinty) {    returnx+y;}voidMain () {structDemo demo; Demo.func=&add2;//struct function pointer assignmentprintf"func (3,4) =%d\n", Demo.func (3,4));}


Pointers to functions in structs

Structs in C are the closest to class concepts, but only members in C-language structs, no functions, but pointers to functions, which makes it easier for us to use functions. For example, the following:

#include <stdio.h> #include <stdlib.h> #include <string.h>typedef struct student{    int id;    Char name[50];     void (*initial) ();    void (*process) (int id, char *name);    void (*destroy) ();} Stu;void Initial () {    printf ("initialization...\n");} void process (int id, char *name) {    printf ("process...\n%d\t%s\n", ID, name);} void Destroy () {    printf ("destroy...\n");} int main () {    stu *stu1;    Both VCs and TC require malloc to function properly, but Linux GCC will be faulted for segment errors and must be malloc    stu1= (stu *) malloc (sizeof (STU));    You must first initialize the    stu1->id=1000;    when you use it strcpy (Stu1->name, "C + +");    stu1->initial=initial;    stu1->process=process;    stu1->destroy=destroy;    printf ("%d\t%s\n", stu1->id,stu1->name);    Stu1->initial ();    Stu1->process (Stu1->id, stu1->name);    Stu1->destroy ();    Free (STU1);    return 0;}

Output:

/*
+ C + +
Initialization ...
Process ...
+ C + +
Destroy ...
*/

In C, how do functions function in a struct? Make the structure similar to the class, let his interior have the property, also has the method
Such structures are generally referred to as protocol classes and provide references:
struct {
int funcid;
Char *funcname;
Int (*funcint) (); /* function pointer int type */
void (*funcvoid) (); /* function pointer void type */
};
Need to initialize every time, more trouble

#include <stdio.h>typedefstruct{intA;void(*pshow) (int);} TMP;voidFunc (TMP *tmp) {    if(Tmp->a >Ten)//if a>10, the callback function is executed. {(TMP->pshow) (tmp->a); }}voidShowinta) {printf ("the value of a is%d\n", a);}voidMain () {TMP test; TEST.A= One; Test.pshow=Show; Func (&test);}/*the general callback function is to use the definition of the structure (the member includes a pointer to the callback function) party B defines the structure variables and registers with party A, party a collects n the register of party B to form the structure chain list, traverses the linked list at a certain time, and makes a callback. When a function pointer is given as a function parameter, passed to a called function, the called function can invoke the external function through this pointer, which forms the callback <p> general program in the function of the callback function is not very obvious, can not use this form </p><p> The main purpose is that when the function is not in the same file, such as a dynamic library, to invoke the function in other programs only in the form of a callback using the function pointer parameters to pass the external function address to implement the call </p><p> function code is modified, do not have to change the library code, Can be implemented normally invoke easy program maintenance and upgrade </p>*/
      1. /*
      2. The general callback function uses:
      3. Party a defines the structure (the member includes a pointer to the callback function)
      4. Party b defines structure variables and registers with party A,
      5. Party a collects n the register of party B to form the structure chain list, traversing the linked list at a certain time, and making a callback.
      6. When a function pointer is a function parameter, it is passed to a called function,
      7. The called function can invoke the external function through this pointer, which forms the callback <p> general program in the function of the callback function is not very obvious, can not use this form </p><p> The main purpose is when the function is not in the same file, such as dynamic libraries, to invoke functions in other programs only in the form of callbacks
      8. Through the function pointer parameter to pass the external function address to implement the call </p><p> function code to make the modification, also does not need to change the library's code, can normally implement the call facilitates the maintenance and the upgrade of the program </p>*/

Reference:
function pointers and functions in C-structured bodies

function pointers Simulate polymorphism

Defining function pointers in structs

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.