C Language Memset Source code
First, usage
void *memset (void *s, int ch, size_t n);
Function: The contents of a piece of memory pointed to by S is all set to the ASCII value specified by CH, the size of the block is specified by the third parameter, and this function usually initializes the newly requested memory.
I don't know if there's anything like me. Memset as a universal initialization tool, such as:
int arr[n];
memset (arr,1,n*sizeof (int));
The ARR array in this way must not be full 0, but 16843009, which explains the reason below.
First, the nature of the variable type is simply the number of bits that the token reads from a memory address, and the cast is the size of the read bit change.
Second, the source code
The following is the implementation of Memset: (code from "C standard Library" P398)
1 void* (Memset) (void*s,intc,size_t N)2 {3 ConstUnsignedCharUC =C;4UnsignedChar*su;5 for(su = s;0< N;++su,--N)6*SU =UC;7 returns;8}
The 3rd line converts C of type int to unsigned char type, which means to truncate the high 24 bits of C, leaving only the lower 8 bits. Line 4th treats S as a unsigned char* type, which means that each element in SU is calculated as 8 bits.
Now take a look at what the code at the beginning of the article will do.
C Binary: 00000000000000000000000000000001 (32-bit)
1, c converted to unsigned char after: 00000001 (8 bit)
2. Assign each element of the pointer su (unsigned char type) (8-bit) a value of 00000001, looping 4n times.
3. After the end of Memset (), each element of ARR is read as type int, 1000000010000000100000001 is read, and decimal is 16843009.
However, if it is memset (arr,0,n*sizeof (int)), then it can be used because 32 bits are 0
Three, efficiency analysis
Again, the efficiency of memset (). Using the Memset function and the above function code written in their own program is not the same, C standard library memset to the use of the cache has been optimized, specifically in the "C expert programming" 151 pages have explained (actually I did not understand), here gives the test:
1#include <string.h>2 #defineMAXSIZE 1000003 4 intMain ()5 {6 CharArr[maxsize];7 for(intI=0;i<10000; i++)8 {9memset (arr,'0',sizeof(arr));Ten //for (int j=0;j<maxsize;j++) One //arr[0] = ' 0 '; A } - return 0; -}
The comment section in the program is used separately from the Memset line, and the result is that the program running with Memset is about 0.1s, and the program with A for loop is 3s long.
All in all: memset () can be used in the initialization of character arrays and similar to memset (arr,0,n*sizeof (int)), where the efficiency is much higher than the manual assignment.
Reference: http://blog.csdn.net/hackbuteer1/article/details/7343189#
C Language Memset Source code