題目一:
- 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
參考鏈接:
1. http://www.cppblog.com/mydriverc/articles/35389.html
2. http://blog.csdn.net/zhoubl668/article/details/6617130
3.http://blog.csdn.net/zhuxiaoyang2000/article/details/8084629