Usage analysis of memset function

  • 2020-04-02 01:03:47
  • OfStack

1. Void *memset(void *s,int c,size_t n)
Overall effect: set the value of the first n bytes of the allocated memory space s to the value c.
2. example

 # include
void main(){
char *s="Golden Global View";
clrscr();
memset(s,'G',6);
printf("%s",s);
getchar();
return 0;
} 

3. The memset() function is often used for memory space initialization. Such as:

char str[100];
memset(str,0,100);

. Deep meaning of memset() : used to set a segment of memory space to a certain character, usually used to initialize the defined string to ' 'or' /0'; Example: char a, [100]. Memset (a, '/' 0 ', sizeof (a));
Memcpy is used for making memory copies. You can copy objects of any data type with memcpy. You can specify the length of the data to be copied. [100] : char a, b [50]; Memcpy (b, a, sizeof (b)); Note that if sizeof(a) is used, the memory address of b will overflow.
Strcpy can only copy strings, so it ends up with '/0'; [100] : char a, b [50]; Strcpy (a, b); If strcpy(b,a) is used, please note whether the string length in a (before the first '/0') exceeds 50 bits. If it exceeds, the memory address of b will overflow.
5. Bonus: a few tips
Memset is a handy way to clean up variables or arrays of structure types.
Such as:

struct sample_struct
{
char csName[16];
int iSeq;
int iType;
};

The variable
Struct sample_strcut stTest;
In general, the method to clear stTest:

stTest.csName[0]='/0';
stTest.iSeq=0;
stTest.iType=0;

Memset is handy:
Memset (& stTest, 0, sizeof (struct sample_struct));
If it's an array:
Struct sample_struct TEST [10].
the
Memset (TEST, 0, sizeof (struct sample_struct) * 10);
6. strcpy
Prototype: extern char *strcpy(char *dest,char * SRC);
Usage: # I nclude
Function: copies the null-terminated string referred to by SRC into the array referred to by dest.
Note: the memory area indicated by SRC and dest may not overlap and dest must have enough space to hold the SRC string.
Returns a pointer to dest.
memcpy
Prototype: extern void *memcpy(void *dest, void * SRC, unsigned int count);
Usage: # I nclude
Function: copy count bytes from the SRC indicated memory region to the dest indicated memory region.
Note: the memory region indicated by SRC and dest cannot overlap. The function returns a pointer to dest.
memset
Prototype: extern void *memset(void *buffer, int c, int count);
Usage: # I nclude
Function: set the first count bytes of the buffer to the character c.
Returns a pointer to a buffer.  

Related articles: