深拷貝和淺拷貝

 

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct Teacher
{
    char name[64];
    int age;
    char *pname2;
}teacher;

/*
編譯器的=號操做會把指針變量的值,從from copy到to
但不會把指針變量所值的內存空間給copy過去 
這就是淺拷貝的機率

對於結構體中含有一級指針或二級指針
須要執行深拷貝,即顯示分配內存,而且執行指針賦值操做
strcpy或者memcpy 
*/
void copyTeacher(Teacher *to, Teacher *from)
{
    *to = *from;
    
    to->pname2 = (char *)malloc(100);
    strcpy(to->pname2, from->pname2);
}

int main()
{
    Teacher t1;
    Teacher t2;
    
    strcpy(t1.name,"name1");
    t1.age = 18;
    t1.pname2 = (char *)malloc(100);
    strcpy(t1.pname2,"ssss");
    
    copyTeacher(&t2,&t1);
    
    printf("%s\n%d\n%s",t2.name,t2.age,t2.pname2);
    
    if(t1.pname2 != NULL)
    {
        free(t1.pname2);
        t1.pname2 = NULL;
    }
    if(t2.pname2 != NULL)
    {
        free(t2.pname2);
        t2.pname2 = NULL;
    }
    
    return 0;
}
相關文章
相關標籤/搜索