Блог пользователя s2kings2

Автор s2kings2, 9 лет назад, По-английски

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
  • Проголосовать: не нравится

»
9 лет назад, # |
  Проголосовать: нравится +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.

»
9 лет назад, # |
  Проголосовать: нравится +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 11111111

2's complement representation of 0 in 32 bits : 00000000 00000000 00000000 00000000

So 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 : 00000010000000100000001000000010

which actually is 33686018.

Program to support the above fact : https://ideone.com/V3j98N

»
9 лет назад, # |
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? :)

»
9 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

Thank you riadwaw, But can u tell me what about Big-O of std::fill function with memset() funtion, thank you!