Search code examples
c++memset

Byte setting an unsigned short


I'm trying to set the bytes in an unsigned short variable individually using memset:

#include <cstring>
#include <iostream>

int main()
{
  unsigned short test2; // 2 bytes

  std::cout << "size of test2: " << sizeof(test2) << std::endl;

  memset(&test2, 0, 2); 
  memset(&test2, 0x4D, 1);                                                               
  memset(&test2+1, 0x42, 1); 

  std::cout << "value: " << test2 << std::endl;

  return 0;
}

The output I'm getting is:

size of test2: 2
value: 77

77 is 0x4D. So for some reason it's not picking up the 0x42 that I'm trying to set on the second byte of the variable. Why is that?


Solution

  • &test2+1 will actually progress the address by sizeof(test2), which is 2, and move the pointer to out-of-range.

    Try this with casting to char*:

    #include <cstring>
    #include <iostream>
    
    int main()
    {
      unsigned short test2; // 2 bytes
    
      std::cout << "size of test2: " << sizeof(test2) << std::endl;
    
      memset(&test2, 0, 2); 
      memset(&test2, 0x4D, 1);                                                               
      memset((char*)&test2+1, 0x42, 1); 
    
      std::cout << "value: " << test2 << std::endl;
    
      return 0;
    }