Memset, the fundamental difference between memcpy and strcpy?

Source: Internet
Author: User

Original address:


memset is used to set all the memory space to a certain character, generally used to initialize the defined string to "or";

Example: Char a[100];memset (A, ' n ', sizeof (a));

Memset can easily empty a variable or array of a struct type.

Such as:

Char csname[16];
int iSeq;
int itype;

For variables
struct Sample_strcut sttest;

In general, the method of emptying the sttest:

Sttest.csname[0]= ' ";

It is very convenient to use memset:
memset (&sttest,0,sizeof (struct sample_struct));

If it is an array:

struct sample_struct test[10];
memset (test,0,sizeof (struct sample_struct) *10);

memcpy is used to make a memory copy, you can copy any data type object, you can specify the data length of the copy.

Example: Char a[100],b[50]; memcpy (b, A, sizeof (b)); Note that using sizeof (a) can cause B's memory address to overflow.

Strcpy can only copy the string, it encounters ' "and ends the copy.

For example: Char a[100],b[50];strcpy (A,B), if used strcpy (b,a), note whether the string length in a (before the first ' "") exceeds 50 digits, such as exceeding, will result in B's memory address overflow.

STR can also be used with a parameter of strncpy (A,b,n)


The main application of memset is to initialize a memory space.
memcpy is used in the copy source space for data to the destination space.
strcpy is used for string copy, encounters ' the ' and ends.

If you understand this, you should know the difference: for example, when you initialize a piece of space, use the memcpy, then how to write, is not very stupid.
int m[100]
memset ((void*) m,0x00,sizeof (int) *100)//ok.
memcpy ((void*) m, "\0\0\0\0 ...", sizeof (int) *100)//it ' s wrong. Feedback

Related Article

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: 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.