指针函数
指针函数,简略了解就是一个返回指针的函数,其本质是一个函数,而该函数的返回值是一个指针。申明格局如下:
*类型标识符 函数名(参数表)
例如,
int *myfun(int x,int y);
留神:在函数名后面多了一个*号,而这个函数就是一个指针函数。其返回值是一个 int 类型的指针。
#include <iostream>using namespace std;#include<string.h>int *newAdd(int a, int b); // 申明指针函数int main() { int *p1 = NULL; p1 = newAdd(1, 2); printf("p1 = 0x%x \n", p1); printf("*p1 = %d \n", *p1); getchar(); return 0; }int *newAdd(int a, int b) { int *p = (int *)malloc(sizeof(int)); memset(p, 0, sizeof(int)); printf("函数内:p = 0x%x \n", p); *p = a + b; printf("函数内:*p = %d \n", *p); return p;}
留神:在调用指针函数时,须要一个同类型的指针来接管其函数的返回值。
也能够将其返回值定义为 void*
类型,调用时强制转换返回值为想要的类型。
函数指针
函数指针,其本质是一个指针变量,该指针指向这个函数。函数指针就是指向函数的指针。申明格局如下:
类型说明符 (*函数名) (参数)
例如,
int (*myfun)(int x,int y);
把一个函数的地址赋值给函数指针变量有两种写法:
myfun = &Function;myfun = Function;
留神:&
不是必须的,因为一个函数标识符就示意了它的地址。
调用函数指针的形式也有两种:
x = (*myfun)();x = myfun();
指针数组
指针数组的定义:type* pArray[n];
例如, int* pa[3]
指针数组中每个元素为一个指针
type*
为数组中每个元素的类型
pArray
为数组名
n
为数组大小
例如,
#include <iostream>using namespace std;#include <string.h>int lookup_keyword(const char* key, const char* table[], const int size){ int ret = -1; int i = 0; for(i=0; i<size; i++) { if(strcmp(key, table[i]) == 0) { ret = i; break; } } return ret;}#define DIM(a) (sizeof(a)/sizeof(*a))int main(){ const char* keyword[] = { "do", "for", "if", "register", "return", "switch", "while", "case", "static" }; cout << lookup_keyword("return", keyword, DIM(keyword)) << endl; cout << lookup_keyword("main", keyword, DIM(keyword)) << endl;}
数组指针
数组指针用于指向一个数组。
数组名是数组首元素的起始地址,但并不是数组的起始地址
通过将取地址符&作用于数组名能够失去数组的起始地址,例如,&array
可通过数组类型定义数组指针: ArrayType* pointer;
例如, array int* pc
也能够间接定义:type (*pointer)[n];
例如,int (*pc)[5]
pointer
为数组指针变量名
type
为指向的数组的类型
n
为指向的数组的大小
#include <iostream>using namespace std;typedef int(AINT5)[5];typedef float(AFLOAT10)[10];typedef char(ACHAR9)[9];int main(){ AINT5 a1; float fArray[10]; AFLOAT10* pf = &fArray; ACHAR9 cArray; char(*pc)[9] = &cArray; int i = 0; printf("%d, %d\n", sizeof(AINT5), sizeof(a1)); for(i=0; i<10; i++) { (*pf)[i] = i; } for(i=0; i<10; i++) { printf("%f\n", fArray[i]); } printf("%0X, %0X\n", &cArray, pc+1);}
回调函数
概念
回调函数,顾名思义,就是使用者本人定义一个函数,使用者本人实现这个函数的程序内容,而后把这个函数作为参数传入他人(或零碎)的函数中,由他人(或零碎)的函数在运行时来调用的函数。函数是你实现的,但由他人(或零碎)的函数在运行时通过参数传递的形式调用,这就是所谓的回调函数。简略来说,就是由他人的函数运行期间来回调你实现的函数。
//一般的hello world实现int main(int argc,char* argv[]){ printf("Hello World!\n"); return 0;}//将它批改成函数回调款式://定义回调函数void PrintfText() { printf("Hello World!\n");}//定义实现回调函数的"调用函数"void CallPrintfText(void (*callfuct)())//传入函数指针{ callfuct();}//在main函数中实现函数回调int main(int argc,char* argv[]){ CallPrintfText(PrintfText); return 0;}