//C語言中的深拷貝和淺拷貝 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct _student{ char name[30]; char *title; int age; }Student; void main(){ Student s1; Student s2; s1.age = 12; strcpy(s1.name, "小明"); s1.title = (char *)malloc(sizeof(char)* 30); strcpy(s1.title, "總經理"); s2 = s1; printf("s1的age=%d,s1的name=%s,s1的title=%s\n", s1.age, s1.name, s1.title); printf("s2的age=%d,s2的name=%s,s2的title=%s\n", s2.age, s2.name, s2.title); printf("s1的地址%x\n", s1.title); //打印b71408 printf("s2的地址%x\n", s2.title); //打印b71408 printf("s1的地址%x\n", s1.name); //打印d5fd18 printf("s2的地址%x\n", s2.name); //打印d5fce8 //這說明s1和s2中成員char *title;只是淺拷貝,兩個指針指向同一塊堆內存, //當釋放free(s1.title);時,s2.title指向的內存空間也沒釋放了,所以再次釋放會報錯 if (s1.title != NULL) { free(s1.title); } //錯誤代碼 /*if (s2.title != NULL) { free(s2.title); }*/ //要想實現深拷貝,那么必須給s2.title也分配一段內存空間, //然后通過strcpy()將s2.title指向的字符串復制到s2.title指向的內存空間內 //由此證明,結構體之間的賦值(s2 = s1;),是進行了結構體內部所有數據的拷貝, //如上s1.name的地址s2.name的地址不同,說明是把s1.name中的數據復制到了s2.name中 system("pause"); }