Hi, all friend! When I use: void * memset ( void * ptr, int value, size_t num ); function in C++, I try to use set all value of my integer array, But why I only set it whith value 0 or -1 otherwise I won't be able to set any other value? Friends Please help me about this case? Thank you very much!








Because memset assigns each bytes in the array to
value. If your array is array ofint, an element has 4 bytes. Therefore, if you codememset(a, 0x3f, sizeof a), each elements ofawill be0x3f3f3f3f.What does it mean by 0x3f?
did you really have to necropost a 7 years old post to learn that
0x3fmeans the value $$$\text{3f}$$$ in hexadecimalThe function memset, sets num number of bits with each 8 continuous bits representing a value. You can't initialize an integer array as an integer is represented by 32bits. memset can be used for data types storing in 8bits (or 1 byte) like char.
Now if we fill an integer 4 times with 8 bits of -1 and 0.
These two numbers will remains same in 32bits representation.
2's complement representation of -1 in 32 bits:
11111111 11111111 11111111 111111112's complement representation of 0 in 32 bits :
00000000 00000000 00000000 00000000So value of -1 and 0 still remains same in 32 bits representation after concatenating 4 8bits 0 and -1.
Now suppose you memset to 2.
Then the array will store values of 4 concatenations of 8-bit representation of 2. that will be :
00000010000000100000001000000010which actually is 33686018.
Program to support the above fact : https://ideone.com/V3j98N
Thank you kien_coi_1997 , mishraiiit but I wonder When we wanna set value of array according to mind, Can we do it? :)
you may use std::fill
Thank you riadwaw, But can u tell me what about Big-O of std::fill function with memset() funtion, thank you!
Well, both of them O(number of v elements filled), but memset is faster