Use of the Memset function

The use of the Memset function
header file:
C:<memory.h>/<string.h>
C++:< cstring >
When I first started using memset, I always thought that memset was assigned to each int. The for loop initializes the array. But in fact, the function of memset is to copy the numbers into the specified memory in a single byte-by-byte copy.

memset(dp,0,sizeof(dp));  

Variables of type int generally occupy 4 bytes. If you assign 0 to each byte, it becomes "00000000 00000000 000000000 00000000" (that is, 0 in decimal)

memset(dp,-1,sizeof(dp));  

If you assign a value of -1, you put "11111111 11111111 11111111 11111111" (-1 in decimal)
so you may think that if you assign a value of 1, every int in the entire dp array will become 1, but it is not.

memset(dp,1,sizeof(dp));  

After the above code is executed, the content of the dp array is 00000001 00000001 00000001 00000001, which is not 1 after conversion to decimal

We see code like this in many programs,

memset(a,127,sizeof(a));

What special number is 127? Through basic hexadecimal conversion, we can know that the binary representation of 127 is 01111111, then the content in the dp array is "01111111 01111111 01111111 01111111", (decimal 2139062143), so that all elements in the array are realized. The purpose of initializing to a large number is needed in the shortest path problem and many other algorithms. It is worth noting that the range of int type is 2^31-1, which is about 2147483647 (if I remember correctly), so the initialized array of int type can also use the value of 127.

What if it was 128? Because the binary of 128 is 10000000, then the content is 10000000 10000000 10000000 10000000. After calculation, the number is -2139062144. This will initialize the array to a small number.

memset(a,128,sizeof(a));

An array of type char can be assigned any value:
1:char map[2][2];

         memset(map, 5, sizeof(map));

2:int map[2][2];

         memset(map, -1, sizeof(map));

Note:
If ptr points to char, the initialization value is arbitrary.
If ptr points to other (such as int), the initialization value can only be -1 or 0.
Remember not to set an array of int type to 1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325686085&siteId=291194637