s2kings2's blog

By s2kings2, 10 years ago, In English

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!

  • Vote: I like it
  • +4
  • Vote: I do not like it

»
10 years ago, # |
  Vote: I like it +3 Vote: I do not like it

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 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    What does it mean by 0x3f?

    • »
      »
      »
      2 years ago, # ^ |
        Vote: I like it -7 Vote: I do not like it

      did you really have to necropost a 7 years old post to learn that 0x3f means the value $$$\text{3f}$$$ in hexadecimal

»
10 years ago, # |
  Vote: I like it +3 Vote: I do not like it

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

»
10 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Thank you kien_coi_1997 , mishraiiit but I wonder When we wanna set value of array according to mind, Can we do it? :)

»
10 years ago, # |
  Vote: I like it +1 Vote: I do not like it

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

  • »
    »
    10 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    Well, both of them O(number of v elements filled), but memset is faster