2026/4/18 9:33:31
网站建设
项目流程
承德网站网站建设,wordpress 定制页面,网站建设开票写什么,如何让搜索引擎不收录网站memcpy - 内存拷贝
void *memcpy(void *destination, const void *source, size_t num);从source位置开始向后复制num个字节到destination指向的内存位置不会在遇到’\0’时停下来如果source和destination有重叠#xff0c;复制结果是未定义的适用于非重叠内存区域的拷贝
使用…memcpy - 内存拷贝void*memcpy(void*destination,constvoid*source,size_t num);从source位置开始向后复制num个字节到destination指向的内存位置不会在遇到’\0’时停下来如果source和destination有重叠复制结果是未定义的适用于非重叠内存区域的拷贝使用示例#includestdio.h#includestring.hintmain(){intarr1[]{1,2,3,4,5,6,7,8,9,10};intarr2[10]{0};memcpy(arr2,arr1,20);// 拷贝20个字节(5个int)for(inti0;i10;i){printf(%d ,arr2[i]);}// 输出: 1 2 3 4 5 0 0 0 0 0return0;}模拟实现void*memcpy(void*dst,constvoid*src,size_t count){void*retdst;assert(dst);assert(src);/* copy from lower addresses to higher addresses */while(count--){*(char*)dst*(char*)src;dst(char*)dst1;src(char*)src1;}returnret;}memmove - 可处理重叠的内存拷贝void*memmove(void*destination,constvoid*source,size_t num);与memcpy功能类似但可以处理源内存块和目标内存块重叠的情况如果源空间和目标空间出现重叠必须使用memmove函数使用示例#includestdio.h#includestring.hintmain(){intarr1[]{1,2,3,4,5,6,7,8,9,10};memmove(arr12,arr1,20);// 将前5个元素拷贝到从第3个元素开始的位置for(inti0;i10;i){printf(%d ,arr1[i]);}// 输出: 1 2 1 2 3 4 5 8 9 10return0;}模拟实现void*memmove(void*dst,constvoid*src,size_t count){void*retdst;if(dstsrc||(char*)dst((char*)srccount)){/* Non-Overlapping Buffers - 从低地址向高地址拷贝 */while(count--){*(char*)dst*(char*)src;dst(char*)dst1;src(char*)src1;}}else{/* Overlapping Buffers - 从高地址向低地址拷贝 */dst(char*)dstcount-1;src(char*)srccount-1;while(count--){*(char*)dst*(char*)src;dst(char*)dst-1;src(char*)src-1;}}returnret;}memset - 内存设置void*memset(void*ptr,intvalue,size_t num);将内存中的值以字节为单位设置成指定内容常用于初始化内存区域或清空数组使用示例#includestdio.h#includestring.hintmain(){charstr[]hello world;memset(str,x,6);// 将前6个字节设置为xprintf(%s\n,str);// 输出: xxxxxxworld// 也可以用于初始化数组intarr[10];memset(arr,0,sizeof(arr));// 将整个数组初始化为0return0;}memcmp - 内存比较intmemcmp(constvoid*ptr1,constvoid*ptr2,size_t num);比较从ptr1和ptr2指针开始向后的num个字节按无符号字符的方式逐字节比较返回值含义0第一个不匹配的字节在prt1中的值小于prt2中的值0两个内存块的内容相等0第一个不匹配的字节在prt1中的值大于prt2中的值使用示例#includestdio.h#includestring.hintmain(){charbuffer1[]DWgaOtP12df0;charbuffer2[]DWGAOTP12DF0;intn;nmemcmp(buffer1,buffer2,sizeof(buffer1));if(n0)printf(%s is greater than %s.\n,buffer1,buffer2);elseif(n0)printf(%s is less than %s.\n,buffer1,buffer2);elseprintf(%s is the same as %s.\n,buffer1,buffer2);return0;}