结构体的赋值

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 struct MyStruct
 5 {
 6     int a[5];
 7     char str[10];
 8     char *p;
 9 };
10 
11 void main()
12 {
13     //  数组 变量没有深浅拷贝的差别  只有指针有
14     // 结构体的赋值内部原理是 memcpy
15     struct MyStruct my1 = { {1,2,3,4,5},"calc",NULL };
16     my1.p = malloc(30);
17     strcpy(my1.p,"hellochina"); // 浅拷贝
18     struct MyStruct my2 = my1;
19     my1.a[3] = 123;
20     my1.str[2] = 'X';
21     *(my1.p) = 'X';
22 
23     for (int i = 0; i < 5; i++)
24     {
25         printf("%d , %d \n",my1.a[i],my2.a[i]);
26     }
27 
28         printf("%s , %s \n", my1.p, my2.p);
29 
30         printf("%s , %s \n",my1.str,my2.str);
31 
32     system("pause");
33 }
34 /******************************运行结果**************************/
35 
36 /*
37     
38     1 , 1 
39     2 , 2 
40     3 , 3 
41     123 , 4 
42     5 , 5 
43     Xellochina , Xellochina 
44     caXc , calc 
45     请按任意键继续. . .
46 
47 */

 

posted on 2015-05-17 15:31  Dragon-wuxl  阅读(120)  评论(0)    收藏  举报

导航