结构体拷贝

 

成员变量包含指针的结构体进行拷贝时,可采取内存整体分配的方法。

好处:大量拷贝操作中,可减少内存碎片;还有,对于调试也比较方便。

举例:

typedef struct _PORT_INFO_2 {
  LPTSTR pPortName;
  LPTSTR pMonitorName;
  LPTSTR pDescription;
  DWORD  fPortType;
  DWORD  Reserved;
} PORT_INFO_2, *PPORT_INFO_2;


//already have a variable :

PORT_INFO_2 * pPortInfo2;

//count size

DWORD dwNeeded = sizeof(PORT_INFO_2)
                                                           + (  lstrlen(pPortInfo2.pPortName)    + 1
                                                           + lstrlen(pPortInfo2.pMonitorName) + 1 
                                                           + lstrlen(pPortInfo2.pDescription) + 1) * sizeof(TCHAR);

PORT_INFO_2 * pPI2 = GlobalAlloc(GPTR,dwNeeded);

//copy

CopyMemory(pPI2 , &(pPortInfo2), sizeof(PORT_INFO_2));
pPI2 ->pPortName    = (LPTSTR)((LPBYTE)pPI2 + sizeof(PORT_INFO_2));
pPI2 ->pMonitorName = (LPTSTR)((LPBYTE)(pPI2 ->pPortName) + (lstrlen(pPortInfo2.pPortName) + 1) * sizeof(TCHAR));

......

//copy struct  member......

lstrcpy(pPI2->pPortName,  pPortInfo2.pPortName);

......

你可能感兴趣的:(C/C++,Coding)