指针函数详解

  • Post author:
  • Post category:其他


指针函数

函数返回值为地址的的函数称为指针函数。

例如:

#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;

}



版权声明:本文为m0_65010117原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。