Byte sets unsigned short

I am trying to set 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 get is:

size of test2: 2
value: 77

77 - 0x4D. Therefore, for some reason, it does not raise 0x42, which I am trying to set on the second byte of a variable. Why is this?

+4
source share
2 answers

&test2+1will actually push an address sizeof(test2)that is 2, and move the pointer to out of range mode.

Try to do this with 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;
}
+6
source

&test2+1 , unsigned short, test2 , test2. unsigned short, , , undefined.

&test2 char *, 1 ():

memset((char *)&test + 1, 0x42, 1);

memset():

unsigned short setbytes(unsigned char hi, unsigned char lo)
{
    return hi << 8 | lo;
}

...    

    unsigned short test2 = setbytes(0x42, 0x4D); /* --> 0x424D */
+1

Source: https://habr.com/ru/post/1648907/


All Articles