A brief analysis of the difference between memset memcpy and strcpy in C++

  • 2020-04-02 01:07:13
  • OfStack


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

//Memcpy: copy by byte
 Prototype: extern void* memcpy(void *dest,void *src,unsigned int count)
//Function: copy count bytes from the memory region indicated by SRC to the memory region indicated by dest;
//With a 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: copies a string and ends at '0'
//Extern char *strcpy(char *dest,char * SRC)
//Function: copy the SRC string ending with '0' into the array denoted by dest;
//Note: the memory area indicated by SRC and dest is not allowed to overlap and dest must have enough space to hold the string. Returns the dest pointer.
char *strcpy_su(char *dest,char *src)
{
       assert((dest!=NULL)&&(src!=NULL));
       char *address = dest;
       while((*dest++=*src++)!='0')
              continue;
       return dest;
}
//Memset: sets the first count bytes of the memory region referred to by the buffer, using the character c instead
//Prototype: 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("%sn",str1);

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

      
       memcpy(str1, str2, strlen(str2));
       printf("%sn",str1);

}

Related articles: