结构体复制与赋值
1 #include <stdio.h>
2 #include <string.h>
3 #include <malloc.h>
4
5 int main(int argc, char* argv[])
6 {
7 struct data
8 {
9 int i;
10 char c;
11 int j;
12 int arr[2];
13 };
14
15
16 struct datawptr
17 {
18 int i;
19 char *c;
20 };
21
22 struct datawptr dptr1;
23 struct datawptr dptr2;
24 struct data svar1; // a normal variable of type struct data
25 struct data svar2; // a normal variable of type struct data
26
27 svar1.c = 'a';
28 svar1.i = 1;
29 svar1.j = 2;
30 svar1.arr[0] = 10;
31 svar1.arr[1] = 20;
32
33 svar2 = svar1;
34 printf("Value of second variable \n");
35 printf("Member c = %c\n", svar2.c);
36 printf("Member i = %d\n", svar2.i);
37 printf("Member j = %d\n", svar2.j);
38 printf("Member arr0th = %d\n", svar2.arr[0]);
39 printf("Member arr1st = %d\n", svar2.arr[1]);
40
41 dptr1.i = 10;
42 dptr1.c = (char*)malloc(sizeof(char));
43 *(dptr1.c) = 'c';
44 dptr2.c = (char*)malloc(sizeof(char));
45 dptr2 = dptr1;
46
47 /* But, with
48 the above approach, one needs to be careful when a data structure contains a member of pointer type because the
49 assignment operator simply copies the value; it will also copy the pointer variable’s value, which is nothing but the
50 address of some variable it is pointing to. */
51
52 printf("int member = %d\n", dptr2.i);
53 printf("char ptr member = %c\n", *(dptr2.c));
54
55 return 0;
56 }
57
58 /*
59 Value of second variable
60 Member c = a
61 Member i = 1
62 Member j = 2
63 Member arr0th = 10
64 Member arr1st = 20
65 int member = 10
66 char ptr member = c
67 */