一、示例,数组存储在内存的栈区,栈还会存函数入口地址等信息,test()调用结束以后会释放ch的存储区,
因此可以看到p没有存到内容。
char * test() { char ch[]="hello"; cout<<"$:"<<&ch<<endl; return ch; } int main() { char *p=test();////////////wrong!! cout<<"#:"<<&p<<endl;
cout<<"*"<<p<<endl; return 0; } /* $:0x6dfeca #:0x6dfefc
*: */
正确的方式:new出的空间存在内存的堆中
char * test() { char *ch=new char[3]; ch[0]='m'; ch[1]='y'; ch[2]='