C语言讲义——指针函数和函数指针
指针函数
返回值是指针的函数,如void* malloc(...)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int *newAdd(int a, int b); // 声明指针函数
main() {
int *p1 = NULL;
p1 = newAdd(1, 2);
printf("p1 = 0x%x \n", p1);
printf("*p1 = %d \n", *p1);
getchar();
}
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;
}
函数中创建“数组”
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int *createArray(int n) {
int *p = (int *)malloc(n * sizeof(int));
memset(p, 0, n * sizeof(int));
int *q = p;
for(int i = 0 ; i<n; i++) {
*(q++) = i*i;
}
return p;
}
main() {
int *p = NULL;
p = createArray(10);
int *q = p;
while(p-q<10) {
printf("%d ", *p);
p++;
}
//TODO:释放内存
}
函数指针
指向函数的指针
#include<stdio.h>
int addition(int x,int y) {
return (x+y);
}
int subtraction(int x,int y) {
return (x-y);
}
int multiplication(int x,int y) {
return (x*y);
}
int division(int x,int y) {
return (x/y);
}
int main() {
int a, b, symbol, ret;
scanf("%d",&a);
getchar();// Enter会被当做输入字符,丢弃
symbol = getchar();
scanf("%d",&b);
switch(symbol) {
case '+':
ret = addition(a, b);
break;
case '-':
ret =subtraction(a,b);
break;
default:
ret = -999;
break;
}
printf("%d%c%d=%d", a,symbol,b,ret);
return 0;
}
每个函数有一个地址,即该函数第一条指令的地址,
可以用一个指针来保存这个地址,而这个指针就是函数指针。
可以用该指针来调用这个函数。
#include<stdio.h>
int addition(int x,int y) {
return (x+y);
}
int subtraction(int x,int y) {
return (x-y);
}
int multiplication(int x,int y) {
return (x*y);
}
int division(int x,int y) {
return (x/y);
}
int main() {
int (*p)(int, int);
int a, b, symbol, ret;
scanf("%d",&a);
getchar();// Enter会被当做输入字符,丢弃
symbol = getchar();
scanf("%d",&b);
switch(symbol) {
case '+':
p = addition;
break;
case '-':
p =subtraction;
break;
default:
ret = -999;
break;
}
ret = (*p)(a,b);
printf("%d%c%d=%d", a,symbol,b,ret);
return 0;
}
函数指针数组
一组指向函数的指针
例:直接计算100*5
#include<stdio.h>
int addition(int x,int y) {
return (x+y);
}
int subtraction(int x,int y) {
return (x-y);
}
int multiplication(int x,int y) {
return (x*y);
}
int division(int x,int y) {
return (x/y);
}
int main() {
int a, b, symbol, ret;
a = 100;
b = 5;
//int (*p)(int, int);
int (*p[])(int, int) = {addition,subtraction,multiplication,division};
ret = (*p[2])(a,b);
printf("%d * %d=%d \n", a,b,ret);
ret = p[2](a,b);
printf("%d * %d=%d \n", a,b,ret);
return 0;
}
运行结果:
100 * 5=500
100 * 5=500