动态内存的传递

  1. /*动态内存传递 
  2. 1 在C中,使用指向指针的指针解决这个问题 
  3. 2 在C++中,使用传递指针的引用 
  4. 3 使用函数返回值来传递动态内存 
  5. */

 

 

void GetMemory1(char **p,int num){  
*p=(char*)malloc(sizeof(char)*num);  
  
}  
  
void GetMemory2(char *&p,int num){  
  
    p=(char*)malloc(sizeof(char)*num);  
}  
  
char* GetMemory3(int num){  
char *p=(char*)malloc(sizeof(char)*num);  
 return p;  
}  
  
int _tmain(int argc, _TCHAR* argv[])  
{  
    char *str1=NULL;  
    char* str2=NULL;  
    char *str3=NULL;  
    char *str4=NULL;  
  
    GetMemory1(&str1,20);  
    GetMemory2(str2,40);  
    str3=GetMemory3(20);  
    strcpy(str1,"GetMemory1");  
    strcpy(str2,"GetMemory2");  
    strcpy(str3,"GetMemory3");  
    cout<<"str1="<<str1<<endl;  
    cout<<"str2="<<str2<<endl;  
    cout<<"str3="<<str3<<endl;  
    cout<<"str1==null?"<<(str4==NULL?"yes":"no")<<endl;  
    free(str1); //释放内存,并把指针赋为NULL  
    free(str2);  
    free(str3);  
    str1=NULL;  
    str2=NULL;  
    str3=NULL;  
    getchar();  
    return 0;  
}  
  

 

  

 

posted @ 2013-11-24 10:17  任智康  阅读(573)  评论(0编辑  收藏  举报