函数怎样返回一个字符串??

折腾_苏州 2005-08-02 05:27:09
#include<iostream.h>
#include<string.h>
char *RoomList() //返回房间列表字符串
{
char roomlist[20]; //定义成数组形式,因为要用到strcat函数

strcpy(roomlist ,"VC");

strcat(roomlist , " | ");

strcat(roomlist , "Linux");

return roomlist;
}
void main()
{
cout<<RoomList()<<endl;
}

输出结果不是 VC | Linux.
roomlist定义成指针类型就可以
这是为什么?
...全文
292 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xjp6688 2005-08-03
  • 打赏
  • 举报
回复
但是要注意空间的释放,还有不能返回栈的指针或者引用
VxD1 2005-08-02
  • 打赏
  • 举报
回复
返回字符串指针
adsfdda 2005-08-02
  • 打赏
  • 举报
回复
恩,局部变量——只在距离它最近的一对大括号内有效,然后就会被释放掉。
#include<iostream.h>
#include<string.h>

char *RoomList(char* roomlist) //返回房间列表字符串
{
// char roomlist[20]; //定义成数组形式,因为要用到strcat函数
strcpy(roomlist, "VC");
strcat(roomlist, " | ");
strcat(roomlist, "Linux");
return roomlist;
}

void main(void)
{
char roomlist[20];
cout<<RoomList(roomlist)<<endl;
}
zyfire88 2005-08-02
  • 打赏
  • 举报
回复
要么定义指针分配内存,要么定义一定量的数组
jixingzhong 2005-08-02
  • 打赏
  • 举报
回复
在你的第二个程序中

char *RoomList(char roomlist[20])

利用的是指针传地址的特性,

可以得到你想要的结果,

这也是我们经常使用的。




这里有一点要注意,

就是在使用这个方法的时候,

不能在函数中对 传递的指针 进行 malloc 或者其他的赋值

(比如定义 char *p="is a boy !";roomlist=p;)

会产生和上面一样的情况!(乱码) 原理是一样的!



如果你不得不在子函数中 对被传递的指针 malloc

可以使用 2级指针

也就是 char *RoomList(char **roomlist) (调用的格式也要相应改变)
heskyII 2005-08-02
  • 打赏
  • 举报
回复
#include<iostream.h>
#include<string.h>
char *RoomList() //返回房间列表字符串
{
char roomlist[20]; //定义成数组形式,因为要用到strcat函数

strcpy(roomlist ,"VC");

strcat(roomlist , " | ");

strcat(roomlist , "Linux");

return roomlist;//此处roomlist是一个被分配在栈上局部变量,在函数RoomList()调用完成后它的存储空间被系统自动回收了,所以返回的内容是不可知的。要么分配在静态存储区(如声明称static类型),要么分配在堆上(使用malloc() or new,但别忘了在程序结束时使用free() or delete(or []delete)释放动态申请的内存空间)
}
void main()
{
cout<<RoomList()<<endl;
}
jixingzhong 2005-08-02
  • 打赏
  • 举报
回复
请不要指望利用函数返回指向栈内存的指针!!



你的函数要求返回指针,

在你的调用函数内,

char roomlist[20];

这个时候 roomlist[20]; 在栈内存中

栈内存中的内容有一个共性

就是当函数返回的时候,

内容会被请空,

所以你的第一个程序,

最后输出的是一些乱码(或者是不确定的东西,而且每次运行都会有不同的内容...)
折腾_苏州 2005-08-02
  • 打赏
  • 举报
回复
后来发现这样也行:

#include<iostream.h>
#include<string.h>
char *RoomList(char roomlist[20]) //返回房间列表字符串
{

strcpy(roomlist ,"VC");

strcat(roomlist , " | ");

strcat(roomlist , "Linux");

return roomlist;
}
void main()
{
chat sTemp[20];
cout<<RoomList(sTemp)<<endl;
}
foochow 2005-08-02
  • 打赏
  • 举报
回复
static char roomlist[20];

/////////或者
#include<iostream.h>
#include<string.h>
char *RoomList() //返回房间列表字符串
{
char*roomlist=new char[20]; //定义成数组形式,因为要用到strcat函数

strcpy(roomlist ,"VC");

strcat(roomlist , " | ");

strcat(roomlist , "Linux");

return roomlist;
}
void main()
{
char*p=RoomList();
cout<<p<<endl;
delete [] p;
}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧