C語言:深複製VS淺複製 陣列VS指標
阿新 • • 發佈:2019-01-23
計算機是32位的,編譯器是dev-cpp。
C原始碼:
#include <stdio.h> struct student{ char *name1; char name2[20]; }stu; int main() { struct student *p; p = &stu; //strcpy((*p).name1,"first");// 編譯正確,執行錯誤,因為沒有分配空間。 strcpy((*p).name2,"second"); // 深複製:複製陣列所有的字元 printf("name1 = %s \t name2 = %s\n",(*p).name1,(*p).name2); p->name1 = "third"; // 淺複製,只複製記憶體地址 printf("name1 = %s \t name2 = %s\n",(*p).name1,(*p).name2); //p->name2 = "fourth"; //編譯錯誤: incompatible types in assignment of `const char[7]' to `char[20]' char tp[20]="fifth"; //p->name2 = tp; //編譯錯誤:ISO C++ forbids assignment of arrays // 深複製和淺複製的區別 strcpy((*p).name2,tp); p->name1 = tp; tp[0]='F';//修改tp字串的值 printf("name1 = %s \t name2 = %s\n",(*p).name1,(*p).name2); // 淺複製的值發生改變,深複製不會 // 字串陣列和指標的區別 printf("sizeof(char *name) = %d\nsizeof(char name[20]) = %d\n", sizeof(p->name1), sizeof(p->name2)); // 32位計算機4和20 system("PAUSE"); return 0; }
執行結果為:
name1 = (null) name2 = second
name1 = third name2 = second
name1 = Fifth name2 = fifth
sizeof(char *name) = 4
sizeof(char name[20]) = 20