码迷,mamicode.com
首页 > 其他好文 > 详细

结构体复制与赋值

时间:2018-09-07 22:51:32      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:include   return   which   app   opera   size   bec   std   argc   

 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 */

 

结构体复制与赋值

标签:include   return   which   app   opera   size   bec   std   argc   

原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/9607281.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!