标签:
深拷贝,拷贝内存的内容,旧结构体发生变化,新结构体也会变化。
浅拷贝,直接地址复制,共享内存,新旧结构体互补影响。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 struct string 8 { 9 char *p; 10 int length; 11 }; 12 13 main1() 14 { 15 struct string str1; 16 str1.length = 10; 17 str1.p = (char *)malloc(sizeof(char) * 10); 18 strcpy(str1.p, "hello"); 19 20 printf("str1.p=%s\n", str1.p); 21 22 struct string str2;//浅拷贝,共享内存 23 str2.length = str1.length; 24 str2.p = str1.p; 25 *(str1.p) = ‘k‘; 26 27 printf("str1.p=%s\n", str1.p); 28 printf("str2.p=%s\n", str2.p); 29 30 system("pause"); 31 } 32 33 main() 34 { 35 struct string str1; 36 str1.length = 10; 37 str1.p = (char *)malloc(sizeof(char) * 10); 38 strcpy(str1.p, "hello"); 39 40 printf("str1.p=%s\n", str1.p); 41 42 struct string str2;//深拷贝 43 str2.length = str1.length; 44 str2.p = (char *)malloc(sizeof(char) * 10); 45 strcpy(str2.p, str1.p); 46 47 printf("str1.p=%s\n", str1.p); 48 printf("str2.p=%s\n", str2.p); 49 50 system("pause"); 51 }
标签:
原文地址:http://www.cnblogs.com/denggelin/p/5571156.html