1. Header file
<memory.h> or <string.h> in C
<cstring> in C++
2. Prototype and function
void *memset(void *s,int c,size_t n)
where s is a pointer or array, c is the value assigned to s, and n is the length of s to be modified, that is, the first n bytes of s.
Function: Set the value of the first n bytes of the allocated memory space s to the value c.
3. Commonly used
It is often used to clear a variable or array of a structure type, such as clearing a structure:
struct sample_struct { char csName[16]; int iSeq; int iType; }; // for variables: struct sample_strcut stTest; //In general, the method of clearing stTest: stTest.csName[0]='/0'; stTest.iSeq=0; stTest.iType = 0; // with 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);
It is also commonly used to initialize memory after malloc applies for a piece of memory:
double* wid = (double*)malloc((num+1) *sizeof(double)); if (wid == NULL) { cout << "Fail to allocate memory to wid" << endl; exit(1); } memset(wid, 0, (num + 1) *sizeof(double));//initialize to 0
4. Pay attention
The function of memset is to copy the numbers into the specified memory in a single byte-by-byte copy .
(1) If ptr points to a char address, value can be any character value;
(2) If ptr points to a non-char type, such as an int type address, if the assignment is to be correct, the value of value can only be -1 or 0, because each bit of -1 and 0 is the same after being converted into binary, set int The type occupies 4 bytes, then -1=0XFFFFFFFF, 0=0X00000000.
Reference: Explanation of the assignment process