---
title: "C++中具有相同内部结构的结构体，可以通过内存拷贝的形式进行复制。"
author: "linger_yan"
date: "2012-06-10T18:21:33Z"
tags: ["code", "struct", "工作"]
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2012-06-10T18:27:04Z"
id: 1557941
url: "https://linger-yan.iteye.com/blog/1557941"
---

今天工作中遇到一个问题，需要进行结构体的复制操作，但是两个结构体的内部结构是完全，只是结构体和结构体内部的命名不一致而已。
一开始想到的肯定是每个字段进行赋值的方法（那个交易的结构体将近二十个字段呢！）。
可回来一想，两个结构体内部结构完全一致，在内存中的存储也应该是一致的，这样是否可以通过内存复制的方式进行结构体的复制，刚才试了试，果然可以。
(如果是两个程序之间进行这样的操作，必须保证结构体的对其方式是完全一致的)

下面是两个结构体声明的代码：

```C++

typedef struct 
{
	char		cSequenceNo[12+1];		
	char		cTotalFee[12+1];
	char		cTest;
	int			iTest;
	char		cOperaotrId[4+1];		
	char		cTimeOut[4+1];	
} ReadCard; 

typedef struct 
{
	char		test1[12+1];
	char		test2[12+1];
	char		cTest;
	int			iTest;
	char		test4[4+1];	
	char		test5[4+1];	
} test; 

```


下面是测试的代码：

```C++


	ReadCard readCard;
	memset(&readCard, 0x00, sizeof(ReadCard));
	
	strcat(readCard.cSequenceNo, "cSequenceNo");
	strcat(readCard.cTotalFee, "cTotalFee");
	strcat(readCard.cOperaotrId, "test");
	strcat(readCard.cTimeOut, "1024");
	readCard.cTest = 'q';
	readCard.iTest = 123;
	
	
	test test1;
	memset(&test1, 0x00, sizeof(test));
	memcpy(&test1, &readCard, sizeof(ReadCard));//就用这么一句就搞定了，呵呵

```