void GetMemory( char **p ) { *p = (char *) malloc( 100 ); } void Test( void ) { char *str = NULL; GetMemory(&str); strcpy( str, "hello world" ); printf( str ); }
是值传递和地址传递的问题。 楼主的题目用的是值传递,在void GetMemory( char *p ) 函数中,会产生p的副本指针(_p),在函数内的一切操作只是在副本中起作用,而p没有丝毫的改变,也就没有起到分配内存的作用了。 void GetMemory( char *p )中的char *p改成:char **p,主函数中传GetMemory(& str); 或改成char *&p,主函数中传GetMemory(str);