将结构体通过memcpy转换为数组

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 /******************
 4 测试将结构体通过memcpy转换为数组的可行性
 5 ******************/
 6 typedef struct TEST
 7 {
 8     short a;
 9     short b;
10     short c;
11 };
12 struct TEST1
13 {
14     char a;
15     short b;
16     int c;
17     char* d;
18 };
19 
20 int main()
21 {
22     struct TEST test;
23     struct TEST1 test1;
24     char tmp[10];
25     short buf[10];
26     char i;
27 
28     test.a = 0x1A10;
29     test.b = 0x2B11;
30     test.c = 0x3C12;
31 
32     memcpy(buf, &test, sizeof(test));
33 
34     printf("sizeof(char) = %d\r\n", sizeof(char));
35     printf("sizeof(short) = %d\r\n", sizeof(short));
36     printf("sizeof(int) = %d\r\n", sizeof(int));
37     printf("sizeof(char*) = %d\r\n", sizeof(char*));
38     printf("sizeof(short*) = %d\r\n", sizeof(short*));
39     printf("sizeof(int*) = %d\r\n", sizeof(int*));
40 
41     printf("\r\nsizeof(test) = %d\r\n", sizeof(test));
42 
43     for(i=0;i<sizeof(test);i++)
44     {
45         printf("buf[%d] = %x\r\n", i, buf[i]);
46     }
47 
48     printf("------------------\r\n");
49 
50     memcpy(tmp, &test, sizeof(test));
51 
52     for(i=0;i<sizeof(test);i++)
53     {
54         printf("tmp[%d] = %x\r\n", i, tmp[i]);
55     }
56 
57     printf("------------------\r\n");
58 
59     printf("sizeof(test1) = %d\r\n", sizeof(test1));
60 
61     test1.a = 0x11;
62     test1.b = 0x1203;
63     test1.c = 0x13243567;
64     test1.d = "ABC";
65 
66     //printf("test1.a = %x\r\n", test1.a);
67     //printf("test1.b = %x\r\n", test1.b);
68     //printf("test1.c = %x\r\n", test1.c);
69     //printf("test1.d = %s\r\n", test1.d);
70 
71     memcpy(buf, &test1, sizeof(test1));
72 
73     for(i=0;i<sizeof(test1);i++)
74     {
75         printf("buf[%d] = %x\r\n", i, buf[i]);
76     }
77 
78     printf("------------------\r\n");
79 
80     memcpy(tmp, &test1, sizeof(test1));
81 
82     for(i=0;i<sizeof(test1);i++)
83     {
84         printf("tmp[%d] = %x\r\n", i, tmp[i]);
85     }
86     return 0;
87 }

结论:可行

posted @ 2020-10-28 13:52  钓梦叟  阅读(1520)  评论(0编辑  收藏  举报