题目一:
- void GetMemory( char *p )
- {
- p = (char *) malloc( 100 );
- }
- void Test( void )
- {
- char *str = NULL;
- GetMemory( str );
- strcpy( str, "hello world" );
- printf( str );
- }
【运行错误】传入GetMemory(char* p)函数的形参为字符串指针,在函数内部修改形参并不能真正的改变传入形参的值。执行完
- char *str = NULL;
- GetMemory( str );
题目二:
- char *GetMemory( void )
- {
- char p[] = "hello world";
- return p;
- }
- void Test( void )
- {
- char *str = NULL;
- str = GetMemory();
- printf( str );
- }
题目三:
- void GetMemory( char **p, int num )
- {
- *p = (char *) malloc( num );
- }
- void Test( void )
- {
- char *str = NULL;
- GetMemory( &str, 100 );
- strcpy( str, "hello" );
- printf( str );
- }
- *p = (char *) malloc( num );
- if ( *p == NULL )
- {
- ...//进行申请内存失败处理
- }
也可以将指针str的引用传给指针p,这样GetMemory函数内部对指针p的操作就等价于对指针str的操作:
- void GetMemory( char *&p) //对指针的引用,函数内部对指针p的修改就等价于对指针str的修改
- {
- p = (char *) malloc( 100 );
- }
- void Test(void)
- {
- char *str=NULL;
- GetMemory(str);
- strcpy( str, "hello world" );
- puts(str);
- }
题目四:
- void Test( void )
- {
- char *str = (char *) malloc( 100 );
- strcpy( str, "hello" );
- free( str );
- ... //省略的其它语句
- }
- str = NULL;
题目五:
- char* GetMemory(int num)
- {
- char* p = (char*)malloc(100);
- return p;
- }
- void Test(void)
- {
- char* str = NULL;
- str = GetMemory(100);
- strcpy(str, "hello");
- cout<<str<<endl;
- }
题目六:
- char* GetMemory(void)
- {
- char* p = "hello world";
- return p;
- }
- void Test(void)
- {
- char* str = NULL;
- str = GetMemory();
- cout<<str<<endl;
- }<strong> </strong>
- strcpy(str, "hello test");
题目七:
- int* GetMemory(int* ptr)
- {
- ptr = new int(999);
- return ptr;
- }
- int main()
- {
- int *ptr1 = 0, *ptr2 = 0;
- ptr1 = GetMemory(ptr2);
- if(ptr1) { cout<<*ptr1<<'\n'; } else { cout<<"ptr1 == NULL\n"; }
- if(ptr2) { cout<<*ptr2<<'\n'; } else { cout<<"ptr2 == NULL\n"; }
- system("pause");
- return 0;
- }
999
ptr2 == NULL
参考链接: