C基础笔记(函数指针)
指针调用:在一个函数里访问另一个函数里的变量
在一个函数里访问另一个函数里的变量 :
#include<stdio.h>
void swap(int* a, int* b);
int main()
{
int a=1;
int b=2;
printf("a=%d,b=%d\n",a,b); // %p表示地址符
swap(&a,&b); //调用swap函数
printf("a=%d,b=%d\n", a,b);
return 0;
}
void swap(int * a,int * b) //交换值
{
int t=*a;
*a=*b;
*b = t;
}
结果:
a=1,b=2
a=2,b=1
函数指针:populate_array() 函数定义了三个参数,第三个参数是函数的指针,通过该函数来设置数组的值
定义回调函数 getNextRandomValue(),使它返回一个随机值,它作为一个函数指针传递给 populate_array() 函数。
#include <stdlib.h> #include <stdio.h> void populate_array(int *array, size_t arraySize, int (*getNextValue)(void)) { for (size_t i=0; i<arraySize; i++) array[i] = getNextValue(); } // 获取随机值 int getNextRandomValue(void) { return rand(); } int main(void) { int myarray[10]; /* getNextRandomValue 不能加括号,否则无法编译,因为加上括号之后相当于传入此参数时传入了 int , 而不是函数指针*/ populate_array(myarray, 10, getNextRandomValue); for(int i = 0; i < 10; i++) { printf("%d ", myarray[i]); } printf("\n"); return 0; }

浙公网安备 33010602011771号