Sometimes write code, always feel that the program to write no problem, but always error, looking for a half-day bug, the original is memset () the use of useless to ... In the final analysis is still too slag, in order to prevent later turn this wrong, specifically to check the information and degrees Niang, a kind of sudden feeling ...
void *memset (void *buffer, int ch, size_t count);
The header file for memset () is #include<string.h>
We often use memset () to initialize arrays, which is much more efficient than initializing for loops
, but it must be clear how it is used, otherwise it is easy to initialize errors.
Memset first parameter fills in the first address of the array, the second parameter fills in the initialization, and the third parameter fills in the byte number. This is what everyone knows.
However, look at the following code
#include <stdio.h>
#include <string.h>
int main ()
{
int a[] = {1,2,3,4,5};
Memset (A, 1, sizeof (a));
for (int i = 0; i < 5; i++)
{
printf ("%d\n", A[i]);
return 0;
}
We want to initialize the array of a[5] to 1, but the output turns out to be
16843009
16843009
16843009
16843009
16843009
The reason for this is that the memset initialization is populated by one byte, the int has four bytes, and is populated with 0000 0001 0000 0001 0000 00001 0000 0001, so that the value of each element in the array is 16843009.
The process of memset () can be summed up in one sentence, starting with parameter 1 to fill the parameter 3 bytes with parameter 2. So if the int a[], change to char a[] The result of output is 1. be interested to play.