c语言的函数指针
- 简单定义并间接调用
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<time.h> void singasong() { printf("%s\n","我爱的你啊,我爱的你,你在哪里啊,在哪里~"); } void main() { void (*p)();//声明一个函数类型指针 p = singasong;//让指针指向定义的函数 p();//间接调用 system("pause"); }
输出结果:
- 直接调用
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<time.h> int gloabalnum = 888; int * getnum() { return &gloabalnum; } void main() { time_t ts;//时间种子类型 int a[10]; int *q = NULL; srand((unsigned int) time(&ts));//随机生成时间种子 for (int i=0; i < 10; i++) { a[i] = rand() % 100; } for (int i = 0; i < 10; i++) { printf("%d\n",a[i]); } q = themax(a,10); printf("最小数是:%d\n", *q); printf("另外,全局变量是%d\n",*(getnum())); system("pause"); }
输出结果:
- 字符串指针相互赋值
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<time.h> void singasong() { printf("%s\n","我爱的你啊,我爱的你,你在哪里啊,在哪里~"); } char * mystrcpy(char * srcstr, char * targetstr) { char * laststr = NULL; if (srcstr == NULL) { targetstr = "哟~您这源字符串空的啊~"; } else { laststr = targetstr; while (*srcstr != '\0') { *targetstr = *srcstr; srcstr++; targetstr++; } *targetstr = '\0';//还是很有必要,否则将跟随乱码 } return laststr; } void main() { //函数返回值是指针 char *z = (char*)malloc(sizeof(char)); char *q = (char*)malloc(sizeof(char)); z = mystrcpy("阿凡提",q); printf("%s\n",z); system("pause"); }