结构体和结构体副本机制
1 #include<stdio.h>
2 #include<stdlib.h>
3
4 struct MyStruct
5 {
6 int a[10];
7 int length;
8 };
9
10 void change(struct MyStruct s1)//副本机制,对于结构体生效(结构体内部有数组,数组生效)
11 {
12 printf("change = %p\n",s1.a);
13 for (int i = 0; i < s1.length; i++)
14 {
15 s1.a[i] = i*3;
16 printf("%d ",s1.a[i]);
17 }
18 }
19
20 void main()
21 {
22 struct MyStruct s1 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9,10 },10 };
23 change(s1);
24 printf("main = %p\n",s1.a);
25 printf("\n");
26 for (int i = 0; i < s1.length; i++)
27 {
28 printf("%d ",s1.a[i]);
29 }
30 system("pause");
31 }
32
33 /////////////////////////////////////////////////////////////////////////////////////////
34
35 // 测试结构体返回值也有副本机制
36
37 struct MyStruct testreturn()
38 {
39 struct MyStruct s1 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 10 };
40 printf("%p,%p", s1.a, s1.a + 1);//int *
41 printf("\n%p,%p", &s1.a, &s1.a + 1);//int (*)[10]
42 return s1;
43 }
44
45 /*
46 typedef int *P;
47 typedef int A[10];//先定义变量,再加上 typdedef,变量名就是新类类型名
48
49 //A returnint() //error C2090: 函数返回数组
50 //{
51 //
52 //
53 //}
54
55 //返回数组的话,这么做
56 struct data
57 {
58 struct info * p;
59 int length;
60 };
61
62 */
63
64 void main()
65 {
66 struct MyStruct s1 = testreturn();
67
68 for (int i = 0; i < s1.length;i++)
69 {
70 printf("%d ",s1.a[i]);
71 }
72 system("pause");
73 }
74
75 ///////////////////////////////////////////////////////////////////////////////
76
77 struct info
78 {
79 char name[10];
80 int age;
81 };
82
83
84 //struct info infos[3] <==> struct info infos[] <==> struct info *infos
85 void changeinfo(struct info infos[])////数组名作为参数退化为指针可以修改
86 {
87 infos[1].age = 99;//修改原本
88 }
89
90 void main()
91 {
92 struct info infos[3] = { { "wu", 18 }, { "zhang", 25 }, { "guo", 29 } };
93 changeinfo(infos);
94 for (int i = 0; i < 3;i++)
95 {
96 printf("%s %d \n",infos[i].name,infos[i].age);
97 }
98
99 system("pause");
100 }
长风破浪会有时,直挂云帆济沧海
posted on 2015-05-18 21:28 Dragon-wuxl 阅读(311) 评论(0) 收藏 举报
浙公网安备 33010602011771号