[[프로그래밍_NOTE]]/C , C++

shollow copy , deep copy

갑빠돌격기 2008. 8. 25. 14:30

// 얕은 복사 문제 //////////////////
// shollow copy error //////////////
#include<stdio.h>
#include<malloc.h>
#include<string.h>

void main()
{
 char *Name1;
 char *Name2;

 char temp[1024];

 printf("이름1 : ");
 gets(temp);
 Name1 = (char*)malloc(strlen(temp)+1);
 strcpy(Name1 , temp);

 Name2 = Name1;
 
 printf("=================\n");
 printf("이름1 : %s\n", Name1);
 printf("이름2 : %s\n", Name2);

 free(Name1);
 free(Name2);
}


// 깊은 복사 //////////////////
// deep copy    //////////////
#include<stdio.h>
#include<malloc.h>
#include<string.h>

void main()
{
 char *Name1;
 char *Name2;

 char temp[1024];

 printf("이름1 : ");
 gets(temp);
 Name1 = (char*)malloc(strlen(temp)+1);
 strcpy(Name1 , temp);

 Name2 = (char*)malloc(strlen(Name1)+1);
 strcpy(Name2 , Name1);
 
 printf("=================\n");
 printf("이름1 : %s\n", Name1);
 printf("이름2 : %s\n", Name2);

 free(Name1);
 free(Name2);
}



// 깊은 복사 함수로 만들기//////////////////
// MyDeepCopy()    //////////////
#include<stdio.h>
#include<malloc.h>
#include<string.h>

void MyDeepCopy(char** ppName1 , char** ppName2)
{
 *ppName2 = (char*)malloc(strlen(*ppName1)+1);
 strcpy(*ppName2 , *ppName1);
}

void main()
{
 char * pName1;
 char * pName2;

 char temp[1024];

 printf("pName1 : ");
 gets(temp);
 pName1 = (char*)malloc(strlen(temp)+1);
 strcpy(pName1 , temp);

 MyDeepCopy(&pName1 , &pName2);
 printf("====================\n");
 printf("pName1 : %s\n" , pName1);
 printf("pName2 : %s\n" , pName2);

 free(pName1);
 free(pName2);
}

사용자 삽입 이미지









사용자 삽입 이미지