目录
二、指针作为参数传递 -----//有两种传参方式:值传递和地址传递
一、函数指针 ----- 保存函数入口地址的指针 例如:
void fun1(void)
{
printf("this is fun1 function!\n");
}
void fun2(void)
{
printf("this is fun2 function!\n");
}
void fun(void(*p)(void))
{
p();
}
int main(void)
{
#if 0
void (*p)(void);
p = fun1;
p();
p = fun2;
p();
#else
fun(fun1);
fun(fun2);
#endif
return 0;
}
二、指针作为参数传递 -----//有两种传参方式:值传递和地址传递
例如:
#include <stdio.h>
int x = 100;
void fun1(int* q1)
{
*q1 = 123;
printf("*q1 = %d\n",*q1);
q1 = &x;
}
void fun2(int **q2)
{
**q2 = 300;
*q2 = &x;
}
int main(void)
{
int a = 120;
int* p = &a;
fun1(p); //p的值-值传递
printf("a = %d\n",a);
printf("*p = %d\n",*p);
fun2(&p); //p的地址-地址传递
printf("a = %d\n",a);
printf("*p = %d\n",*p);
return 0;
}
三、指针函数
函数返回值为地址的的函数称为指针函数。
例如:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//指针函数
char * fun1(void) //返回.rodata段中的地址,只读不能修改地址空间中的数据
{
//return "hello world";
char *p = "hello wrold";
return p;
}
char * fun2(void) //返回.stack段中的地址,函数结束时,空间自动释放,所以不能返回.statck中的地址
{
char p[] = "hell world";
return p;
}
char * fun3(void) //返回.heap段中的地址,返回后空间数据是可读可写的
{
char *p = (char*)malloc(100);
if(p == NULL){
perror("malloc");
exit(1);
}
strcpy(p,"hello world");
return p;
}
char * fun4(void) //返回.data段中的地址,程序不结束p的空间不释放,所以可以返回,且空间数据可读可写
{
static char p[] = "hell world";
return p;
}
void fun(void)
{
printf("hello world\n");
}
typedef void(*FUNTYPE)(void);
//void (*fun5(void))(void)
FUNTYPE fun5(void) //返回.text段中的地址,代码段为只读,不能赋值,返回的函数地址可以调用函数
{
return fun;
}
int main(void)
{
#if 0
char *str;
str = fun4();
printf("str = %s\n",str);
*str = 'H';
printf("str = %s\n",str);
#else
void (*p)(void);
p = fun5();
p();
#endif
return 0;
}