Function prototypes
void *memset (void *s, int ch, unsigned n);
Sets the contents of each byte in a piece of memory pointed to by S to the ASCII value specified by CH, and the size of the block is specified by the third parameter, which is typically initialized for the newly requested memory, and its return value is a pointer to S.
Header file Required
<memory.h> or <string.h>
program Example
#include <string.h>
#include <stdio.h>
#include <memory.h>
int main (void)
{
Char buffer[] = "Hello world\n";
printf ("Buffer before memset:%s\n", buffer);
memset (buffer, ' * ', strlen (buffer));
printf ("Buffer after memset:%s\n", buffer);
return 0;
}
Output results:
Buffer before Memset:hello World
Buffer after Memset: ************
Build Platform:
Microsoft Visual C + + 6.0
It is not necessarily that the content is set to the ASCII value specified by CH, and that the CH can be int or other types, not necessarily the char type. For example, here's how:
int array[5] = {1,4,3,5,2};
for (int i = 0; i < 5; i++)
cout<<array[i]<< "";
cout<<endl;
memset (array,0,5*sizeof (int));
for (int k = 0; k < 5; k++)
cout<<array[k]<< "";
cout<<endl;
The result of the output is:
1 4 3 5 2
0 0 0 0 0
The parameters for the subsequent table size are in bytes, so it is not all the default 1 (character type) for int or others. And the size of the int may be different on different machines, so it's best to use sizeof ().
Note that Memset is an operation on the byte,
So if the above procedure should read
int array[5] = {1,4,3,5,2};
for (int i = 0; i < 5; i++)
cout<<array[i]<< "";
cout<<endl;
memset (array,1,5*sizeof (int));/Note this is different from the program above
for (int k = 0; k < 5; k++)
cout<<array[k]<< "";
cout<<endl;
The result of the output is:
1 4 3 5 2
16843009 16843009 16843009 16843009 16843009
Why, then?
Because the memset is assigned in bytes or 4 bytes to the memory that the array points to, each is populated with ASCII 1 characters, and 1 is 00000001 after the binary, which takes up a byte. An int element is 4 bytes, the oneness is 00000001000000010000000100000001, equals 16843009, and it completes the assignment of an INT element.
Therefore, it is undesirable to use memset to assign an initial value to a non-character array.
For example there is a structural body some x, which can be so clear 0:
memset (&x, 0, sizeof (Some));
If it is an array of structs some x[10], you can do this:
memset (x, 0, sizeof (Some) *10);
The original source from Baidu know: http://zhidao.baidu.com/link?url=2OlERqJVW2K-WdXQEktGkKZGeHTxRj4b_4_hs6VWp9n5F7_ B1la0ibcjeg7fwhwi9fn0r_ecn5yh_sm749zi1_