
- 01 #include "stdafx.h"
- 02 #include <cstring>
- 03
- 04 //PERSON为POD
- 05 struct PERSON
- 06 {
- 07 char _name[16];
- 08 int _age;
- 09 bool _gender;
- 10 };
- 11
- 12 void print(PERSON * p)
- 13 {
- 14 printf("%s,%d,%s\r\n", p->_name, p->_age, (p->_gender ? "男" : "女"));
- 15 }
- 16
- 17 int main()
- 18 {
- 19 //POD对象可以使用初始化列表
- 20 PERSON p1 = {"佟湘玉", 28, false};
- 21 PERSON p3 = {"白展堂", 26, true};
- 22 print(&p1);
- 23 print(&p3);
- 24
- 25 //将p1转储为char数组
- 26 char bytes[sizeof(PERSON)];
- 27 memcpy(bytes, &p1, sizeof(PERSON));
- 28
- 29 PERSON p2;
- 30 memset(&p2, 0, sizeof(PERSON));
- 31 print(&p2);
- 32
- 33 //将char数组还原为p2
- 34 memcpy(&p2, bytes, sizeof(PERSON));
- 35 print(&p2);
- 36
- 37 //将p3复制至p2
- 38 memcpy(&p2, &p3, sizeof(PERSON));
- 39 print(&p2);
- 40
- 41 return 0;42 }
结果输出如图4-5所示。