您的位置:首页 > 其它

函数返回值为字符串的几种写法

2016-06-23 19:58 375 查看
#include <cstdio>
#include <cstring>
#include <iostream>

#include <string>
#include <Windows.h>
using namespace std;
void fun(char *s){//通过形参返回字符串
strcpy(s, "hello");
}
char *fun2(char *s){//另一种写法,
strcpy(s, "hello");
return s;//返回形参地址,方便程序调用
}

char *fun3(void){
static char s[100];//不能使非静态变量,否则子函数结束,局部变量被释放,调用者得到一个无效的地址。
strcat(s, "hello");
return s;
}
char *fun4(void){
char *s;
s = (char *)malloc(100);
strcpy(s, "hello");
return s;//返回s值,该地址需要调用者去free释放
}

//定义全局变量
char globle_buf[100];
void fun5(void){
strcpy(globle_buf, "hello");
}
char *fun6(char *s){//另一种写法
strcpy(globle_buf, "hello");
return globle_buf; //返回全局变量地址,方便程序调用
}
int main(){

char *s2;
fun3();
s2 = fun3();
cout << s2 << endl;
fun3();
cout << s2 << endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: