The C language memset function is explained in detail

  • 2020-06-01 10:26:05
  • OfStack

The C language memset functions are explained in detail

1. void * memset (void*s, int ch,size_t n)

2. The s () function zeros a sequence of n bytes starting with the s memory address into ch, which is used to clear a large number of structures and arrays

3. Common mistakes

1. The positions of ch and n are reversed

For char[20] clear, 1 must be memset(a,0,20);

2. Overuse of memset

3. This error is not strictly memset, but it often occurs when memset is used


int fun(strucy something * a) 
{ 
..... 
memset(a,0,sizeof(a)); 
..... 
} 

The reason for the error here is the pointer degradation during the VC function parameter transfer, resulting in sizeof(a), which returns the number of bytes of the size of an something* pointer type, if it is 32 bits, it is 4 bytes. This form is often used


memset(a,0,n*sizeof(type));

4. Want to initialize the array to 1


int main() 
{ 
   int a[20]; 
   memset(a,1,20); 
}

This method does not initialize to 1. The reason is that the memset function is assigned in bytes, and int is 4 bytes so it's 0x01010101, which is 16843009 in base 10.

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: