内存拷贝探究

来源:互联网 发布:mac eclipse真机调试 编辑:程序博客网 时间:2024/06/14 05:31
函数原型:
errno_t memcpy_s(   void *dest,   size_t numberOfElements,   const void *src,   size_t count );

参数:

dest

新的缓冲区。

numberOfElements

目标缓冲区的大小。

src

要复制的缓冲区。

count

字符数。的副本。

测试代码:

// memcpyTest.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "string" //strlen()需要的头文件int _tmain(int argc, _TCHAR* argv[]){//-----memcpyPchar_Test_Begin-----------------------------// Populate a2 with squares of integerschar *psourcechar = "aaa";char *ptargetchar = /*NULL*/new char[6]; //内存拷贝,需要保证target目标有空间,且要保证空间的大小// Tell memcpy to copy 10 ints (40 bytes)(the size of a1)memcpy(ptargetchar,psourcechar,sizeof(ptargetchar));    ptargetchar[strlen(psourcechar)]='\0';printf("%s ", ptargetchar);printf("\n");//-----memcpyPchar_Test_End-----------------------------//-----memcpy_Test_Begin-----------------------------int memcpya1[10], memcpya2[100], i;// Populate a2 with squares of integersfor (i = 0; i < 100; i++){memcpya2[i] = i*i;}// Tell memcpy to copy 10 ints (40 bytes)(the size of a1)memcpy(memcpya1,memcpya2,sizeof(memcpya1) );    for (i = 0; i < 10; i++)printf("%d ", memcpya1[i]);printf("\n");//-----memcpy_Test_End-----------------------------//-----memcpy_s_Test_Begin-----------------------------int a1[10], a2[100], j;errno_t err;// Populate a2 with squares of integersfor (j = 0; j < 100; j++){a2[j] = j*j;}// Tell memcpy_s to copy 10 ints (40 bytes), giving// the size of the a1 array (also 40 bytes).err = memcpy_s(a1, sizeof(a1), a2, 10 * sizeof (int) );    if (err){printf("Error executing memcpy_s.\n");}else{for (j = 0; j < 10; j++)printf("%d ", a1[j]);}printf("\n");//-----memcpy_s_Test_End-----------------------------return 0;}