第一类问题:z指针作为函数参数的传递问题
在将一个指针传入函数并在函数中为其分配内存空间的时候会出现下面的常用错误:
#include <cstring> using namespace std; //void GetMemory( char *p )//假如这里是*p那么在函数中就不是p指针本身而是临时变量,所以最后分配的空间并不是为原来的p分配的
void GetMemory( char *&p )
{ p = (char *) malloc( 100 ); } void Test( void ) { char *str = NULL; GetMemory( str ); strcpy( str, "hello world" ); // printf( str ); } int main() { char *str = NULL; GetMemory( str ); strcpy( str, "hello world" ); printf( "%s",str); return 0; }
一般有两种解决的思路:
1.将原来的函数参数修改为
void GetMemory( char *&p )
引用传递。这样在函数内部就会为原来的部分分配内存。
2.
返回指针。即使是值传递,将分配的指针传递回去,这样的话也是可以的。
第二类问题:局部变量生存期的问题
char
*GetMemory(
void
)
{
char
p[] =
"hello world"
;
return
p;
}
void
Test(
void
)
{
char
*str = NULL;
str = GetMemory();
printf
( str );
}