请问下边的代码为什么编译无法通过呢

左大神在这 2008-03-09 05:02:35
#include <iostream>
#include <string>
using namespace std;

char *getMemory( void )
{
 char point[] = "hello world"; //这行报编译错this character is not allowed in an identifier
 return point;
}

void testCode( void )
{
 char *str = NULL;
 str = getMemory();
 printf( str );
}
大家帮我修改下,谢谢.
...全文
112 11 打赏 收藏 举报
写回复
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
lxjlan 2008-03-10
  • 打赏
  • 举报
回复
char *getMemory( void )
{
 char point[] = "hello world"; //这行报编译错this character is not allowed in an identifier
 return point;
}

这里有错呀。。。point是在栈区的,这样返回,point会造成错误的。。。在getMemory函数执行结束以后就被释放了。
ttkk_2007 2008-03-10
  • 打赏
  • 举报
回复
你这段代码一定是从其他地方拷贝的,你把代码自己重新敲一遍,就不会有那个问题了
另外,你不要返回指向栈内存的指针

char *getMemory(void){
char *point = new char[12];
strcpy(point, "hello world");
return point;
}

void testCode(void){
char *str = NULL;
str = getMemory();
printf(str);
delete []str;
str = NULL;
}

int main()
{
testCode();
return 0;
}
星光伴月 2008-03-10
  • 打赏
  • 举报
回复
可以将point定义成静态的:
char * GetMemory(){
static char point[]="hello world";
return point;
}
zcl198715 2008-03-10
  • 打赏
  • 举报
回复
5楼的代码没有问题,但写的并不规范,在有点机子上可以没有正常运行!以下是规范的代码:
#include <iostream>
#include <cstring>
using namespace std;

char *getMemory()
{
char *point=new char[12];
strcpy(point,"hello world");
return point;
}

void testCode()
{
char *str = NULL;
str = getMemory();
cout<<str<<endl;;
delete str;
}
int main()
{
testCode();
return 0;
}
zcl198715 2008-03-10
  • 打赏
  • 举报
回复
好一个"半桶水"!那观点你老师这么说过的吗?
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using namespace std;

char *getMemory( void )
{
 char point[] = "hello world"; //这行报编译错this character is not allowed in an identifier
//这里定义point为一个数组,没指定数组大小,当然不行,而且初始化方法也不对。

 return point; //point没固定地址,"hello word"存在随机地址之中,退出本函数后,可能会被其他数据覆盖
}

void testCode( void )
{
 char *str = NULL;
 str = getMemory();
 printf( str );
}
babala520 2008-03-09
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using namespace std;

char *getMemory( void )
{
//char point[] = "hello world";
char *point=new char[12];
strcpy(point,"hello world");
return point;
}

void testCode( void )
{
char *str = NULL;
str = getMemory();
printf( str );
delete str;
}
void main()
{
testCode();
}

你返回的point 是一个临时空间,函数GetMemory()返回时这片空间就被回收了,所以你返回的point是一个垃圾地址,
还有函数调用是不能返回栈中的地址的!
不知道对你有没有帮助,
hastings 2008-03-09
  • 打赏
  • 举报
回复
你new一下,再strcpy一下,最后返回.
wp71105412 2008-03-09
  • 打赏
  • 举报
回复
同意楼上 ~
arong1234 2008-03-09
  • 打赏
  • 举报
回复
除了一些不可见字符的问题,还有这样返回point是不可以的
point是一个临时数组,函数返回就不存在了,你这样返回的指针是不得使用的
HengStar 2008-03-09
  • 打赏
  • 举报
回复
刚试验了一下好像是因为你输入的字符有问题,输入法?总之不能被编译器识别
你把以上重新手动在记事本里输入一次然后粘过来看看还没有错
相关推荐
发帖
C++ 语言

6.3w+

社区成员

C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
帖子事件
创建了帖子
2008-03-09 05:02
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下