第一类问题: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.将原来的函数参数修改为