26.指针作为函数的返回值,函数指针的概念-创新互联
指针作为函数的返回值
当前题目:26.指针作为函数的返回值,函数指针的概念-创新互联
转载源于:http://tyjierui.cn/article/djiopg.html
一个函数可以返回整数数据,字符数据,浮点型数据,也可以返回一个指针。
#includechar* fun(void)
{const char str[100] = "hello world";
return str;
}
int main()
{char* p;
p = fun();
printf("p=%s\n", p);
return 0;
}
总结:返回地址的时候,地址指向的内存内容不能释放。
1.返回静态局部数组的地址#includechar* fun(void)
{static char str[100] = "hello world";
return str;
}
int main()
{char* p;
p = fun();
printf("p=%s\n", p);
return 0;
}
char* fun(void)
{char* str = "hello world";
return str;
}
int main()
{char* p;
p = fun();
printf("p=%s\n", p);
return 0;
}
#include#include#includechar* fun(void)
{char* str;
str = (char*)malloc(100);
strcpy_s(str,100,"hello world");
return str;
}
int main()
{char* p;
p = fun();
printf("p=%s\n", p);
free(p);
return 0;
}
总结:返回的地址,地址指向的内存的内容得存在,返回的地址才有意义。
- 定义的函数,在运行程序的时候,会将函数的指令加载到内存的代码段。所以函数也有起始地址。
- C语言规定:函数的名字就是函数的首地址,即函数的入口地址。
- 定义一个指针变量,来存放函数的地址,这个指针变量就是函数指针。
函数指针用来保存函数的入口地址。
在项目开发中,我们经常要编写或者调用带函数指针参数的函数。
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
当前题目:26.指针作为函数的返回值,函数指针的概念-创新互联
转载源于:http://tyjierui.cn/article/djiopg.html