C ++: the fundamental difference between memset, memcpy and strcpy!

Source: Internet
Author: User

# 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 area indicated by src to the memory area indicated by dest;

// Same as 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: copy the string. It ends when '\ 0' is encountered.

// Prototype: extern char * strcpy (char * dest, char * src)

// Function: copy the src string ending with '\ 0' to the array indicated by dest;

// Note: the memory areas specified by src and dest cannot overlap and the dest must have enough space to hold strings. 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: set the first count byte of the memory area referred to by the buffer, which is replaced by the character c.

// 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 ("% s \ n", str1 );

 

 

Char a [3];

Memset (a, 'A', sizeof (a)-1 );

Memset (& a [2], '\ 0', 1 );

Printf ("% s \ n", );

 

Memcpy (str1, str2, strlen (str2 ));

Printf ("% s \ n", str1 );

 

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.