### s2kings2's blog

By s2kings2, 8 years ago,

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!

• +4

 » 8 years ago, # |   +3 Because memset assigns each bytes in the array to value. If your array is array of int, an element has 4 bytes. Therefore, if you code memset(a, 0x3f, sizeof a), each elements of a will be 0x3f3f3f3f.
•  » » 2 months ago, # ^ |   0 What does it mean by 0x3f?
•  » » » 2 months ago, # ^ |   -7 did you really have to necropost a 7 years old post to learn that 0x3f means the value $\text{3f}$ in hexadecimal
 » 8 years ago, # |   +3 The 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. 2's complement representation of -1 in 8 bits : 11111111 2's complement representation of 0 in 8 bits : 00000000 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
 » 8 years ago, # | ← Rev. 2 →   0 Thank you kien_coi_1997 , mishraiiit but I wonder When we wanna set value of array according to mind, Can we do it? :)
•  » » 8 years ago, # ^ |   +3 you may use std::fill
 » 8 years ago, # |   +1 Thank you riadwaw, But can u tell me what about Big-O of std::fill function with memset() funtion, thank you!
•  » » 8 years ago, # ^ |   +1 Well, both of them O(number of v elements filled), but memset is faster