http://hi.baidu.com/microgrape/blog/item/ac7c0bcaf57b27f753664f37.html
1.void GetMemory( char *str, int
size )
2.{
3. printf( "address of str = %x/n",& str );
4. str = new char[size+1 ];
5. printf( "address of str = %x/n",& str );
6.}
7.int main()
8.{
9. char *p = "hello" ;
10. printf( "address of p = %x/n", & p );
11. GetMemory( p, 6 );
12. printf( "address of p = %x/n", & p );
13. //strcpy( p, "hello" );
14. return 0 ;
15.}
2.{
3. printf( "address of str = %x/n",& str );
4. str = new char[size+1 ];
5. printf( "address of str = %x/n",& str );
6.}
7.int main()
8.{
9. char *p = "hello" ;
10. printf( "address of p = %x/n", & p );
11. GetMemory( p, 6 );
12. printf( "address of p = %x/n", & p );
13. //strcpy( p, "hello" );
14. return 0 ;
15.}
错误的原因之一就是:程序虽然确实分配了内存,但是并不是分配给了程序中的p,而是分配给了它的副本,因为参数传入函数的时候会自动生成副本。
11行的GetMemory(p, 6)中的p,其实传的是p的右值,即传的是“hello”字符串的首地址。GetMemory的形参str意思是定义一个指针变量,这个指针变量名叫str,里面保存的内容是个指针。这个str是在栈上分配的,因此函数退出时就消失了。这就解释了为什么传递不了分配的内存。引用的文章里面有图很详细的介绍了这个问题。