Tag: Represents the type log returned by the body border return LSP
1. Function pointers
A pointer to a function. Essence is a pointer.
Pointer variables can point to the address of a variable, an array, a string, a dynamically assigned address, and also point to a function, each time a function is compiled, the system assigns a portal address to the function, the function name represents the entry address , and a pointer variable to the function is called a function pointer variable.
引论:intsumup(inta, floatb);int(*p3) (int a, floatb); //加入p3=&sumup;则p3作为指针指向sumup。这就是p3指针指向函数【回顾:两者的返回值和形参都是 int(inta, floatb);】int* (*p4)(inta, floatb);从类型上看,int* (inta, floatb) 是上式函数的指针。故有:p4 = &p3; |
Int (*p) (int x); Declaring a function pointer
The first address of the Func function can be assigned to the pointer p in the following two ways
P=func;
p=&func;
The FETCH address operator & is not required because a function identifier alone represents its address, and if it is a function call, it must also contain a parameter table enclosed in parentheses. There are two ways to invoke a function with pointers:
X= (*p) ();
X=p (); While it looks like a normal call, some programmers tend to use the first format because it explicitly indicates that a function is called by a pointer rather than a function name.
| 1234 |
如使用引论中的例子有如下的调用:sumup (100,1.21);(*p3) (100,1.21); //与上等价*(p4) (100,1.21); //与上等价 |
Sample program:
| 1234567891011121314151617181920212223 |
void(*funcp)();voidFileFunc(),EditFunc(); main(){ funcp=FileFunc; (*funcp)(); funcp=EditFunc; (*funcp)();} voidFileFunc(){ printf(FileFunc\n); } voidEditFunc(){ printf(EditFunc\n);}程序输出为: FileFunc EditFunc |
2. Pointer function refers to a function with pointers,which is essentially a function。function returns theTypeis aA pointer to a type that returns an address to the calling function for use in an expression that requires a pointer or address. type identifier * Function name (parameter table)such as: declaration: Int * F (x); int *p; Call: P=f (a);
| 1234567891011121314151617181920212223 |
int* GetDate(intwk,intdy) //返回某元素的地址{ staticintcalendar[5][7]={ {1,2,3,4,5,6,7}, {8,9,10,11,12,13,14}, {15,16,17,18,19,20,21}, {22,23,24,25,26,27,28}, {29,30,31,-1} }; return&calendar[wk-1][dy-1]; } main(){ intwk,dy; do { printf(Enter week(1-5)day(1-7)\n); scanf(%d%d,&wk,&dy); } while(wk<1 || wk>5 || dy<1 || dy>7); printf(%d\n,*GetDate(wk,dy)); } |
function pointers and pointer functions for C