tips~function pointer

时间:2023-03-09 09:22:29
tips~function pointer

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)(,));
return ;
}

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=; 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[].name="red";
Colors[].red=;
Colors[].name="blue";
Colors[].blue=;
Colors[].name="black"; eachColor(printColor);
}

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