浅析C++中memset,memcpy,strcpy的区别

时间:2021-07-12 20:05:02

复制代码 代码如下:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

//memcpy:按字节复制
原型:extern void* memcpy(void *dest,void *src,unsigned int count)
//功能:由src所指内存区域复制count个字节到dest所指的内存区域;
//同strcpy
void *memcpy_su(void *dest, void *src, unsigned int count)
{

       assert ((dest!=NULL)&&(src!=NULL));
       char* bdest = (char*)dest;
       char* bsrc = (char*) src;
       while(count-->0)
        *bdest++ = *bsrc++;
       return dest;
}

//strcpy:复制字符串,遇到'\0'就结束
//原型:extern char *strcpy(char *dest,char *src)
//功能:把src所指由'\0'结束的字符串复制到dest所指的数组中;
//说明:src和dest所指内存区域是不可以重叠的且dest必须有足够的空间来容纳字符串。返回dest指针。
char *strcpy_su(char *dest,char *src)
{
       assert((dest!=NULL)&&(src!=NULL));
       char *address = dest;
       while((*dest++=*src++)!='\0')
              continue;
       return dest;
}
//memset:设置buffer所指的内存区域的前count个字节,用字符c来代替
//原型:extern void *memset(void *buffer,int c,int count);
 void *memset_su(void *buffer, int c, int count)
{
   assert ((buffer!=NULL));
   char* buffer2 = (char*)buffer;
   while(count-->0)
        *buffer2++ = c;
       return buffer;
}

void main()
{
       char str1[100]="abchjhgjghjgjgh";
       char str2[50]="efghdfkdjf";

       strcpy(str1, str2);
       printf("%s\n",str1);

 
       char a[3];
       memset(a, 'a', sizeof(a)-1);
       memset(&a[2], '\0',1);
       printf("%s\n",a);

     
       memcpy(str1, str2, strlen(str2));
       printf("%s\n",str1);

}