In depth understanding based on memset of function

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

Today write software engineering big job, adjusted half a day of bugs, the original is not in place to memset function knowledge caused by.
Int Max [teachRelationNum];
Memset (Max, 0, sizeof (Max));
Note that you can use sizeof(Max) or sizeof(int)*teachRelationNum, not directly TeachRelationNum, to initialize!
In general, it can be used like this:
Memset (Max, 0, sizeof (Max));
Memset (Max, 1, sizeof (Max));
Memset (Max, 'a', sizeof (Max));
You can't give it an initial value of 100 or something like that, you can only give it an initial value of 100 through the for loop.
Specific use strategies:
contains < String. H >
      Char buffer[] = "Hello world\n";
Printf ("Buffer before memset: %s\n", Buffer);
Memset (buffer, the '*', strlen (buffer));
Printf ("Buffer after memset: %s\n", Buffer);
Output results:
Buffer before memset: Hello world
Buffer after memset: * * * * * * * * * * * *
An int array [5] =,4,3,5,2 {1};
Memset (array, 0, 5 * sizeof (int));
Output results: 0, 0, 0, 0, 0
Memset (array, 1, 5 * sizeof (int)); // note that this is different from the above program
Output: 16843009 16843009 16843009 16843009 16843009 16843009 16843009
Because memset is in bytes, it assigns four bytes of memory that array points to, each of which is filled with characters of ASCII 1. Once converted to binary, 1 is 00000001, or one byte. An INT element is 4 bytes, combined is 00000001000000010000000100000001, and is equal to 16843009, completes the value assigned to an INT elements.
So using memset to assign an initial value to a non-character array is not desirable!
For example, there is a structure, Some x, which can be zeroed out like this:
Memset (&x, 0, sizeof(Some));
If it is an array of Some x[10] of a structure, it can look like this:
Memset (x, 0, sizeof(Some)*10);
The above is a profound study of memset(), part is my own experience, part is from baidu baike.

 


Related articles: