1. 程式人生 > >C++如何將兩塊記憶體的資料合併到一塊記憶體

C++如何將兩塊記憶體的資料合併到一塊記憶體

記憶體資料的拼接,在開發中有時候也會遇到。

記憶體資料p1,記憶體資料p2,拼接為記憶體資料p.

p1拷貝到p的前半部分,p2拷貝到p的後半部分。

可以使用memcpy來進行資料的拷貝拼接,關鍵是要控制好拼接的位置:p2記憶體資料從哪個位置往p裡面拷貝。

例子如下:

<pre name="code" class="cpp">#include <stdio.h>
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
	char a[] = "123";
	char b[] = "45";
	char *pDes = new char[5];

	memcpy(pDes, a, 3);
	memcpy(pDes + 3, b, 2);
	for (int i = 0; i < 5; i++)
		printf("a[%d] = %c\n", i, pDes[i]);
	return 0;
}