首页 > 其他 > 详细

tips~function pointer

时间:2015-12-23 12:42:29      阅读:125      评论:0      收藏:0      [点我收藏+]

An simple example:

#include<stdio.h>

int plus(int a,int b)
{
    return a+b;
}

int main()
{
    int (*func)(int,int);
    func=&plus; //point to the function ‘‘plus(int,int)‘‘
    printf("the result is %d\n",(*func)(4,7));
    return 0;
}

 

Another example:

#include <stdio.h>
#define MAX_COLORS  256

typedef struct {
    char* name;
    int red;
    int green;
    int blue;
} Color;

Color Colors[MAX_COLORS];


void eachColor (void (*fp)(Color *c)) {
    int i;
    for (i=0; i<MAX_COLORS; i++)
        (*fp)(&Colors[i]);
}

void printColor(Color* c) {
    if (c->name)
        printf("%s = %i,%i,%i\n", c->name, c->red, c->green, c->blue);
}

int main() {
    Colors[0].name="red";
    Colors[0].red=255;
    Colors[1].name="blue";
    Colors[1].blue=255;
    Colors[2].name="black";

    eachColor(printColor);
}

 

For more,go to How do function pointers in C work?-Stackoverflow

tips~function pointer

原文:http://www.cnblogs.com/suzyc/p/5069280.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!