fork download
  1. #include <cstdint>
  2. #include <iomanip>
  3. #include <iostream>
  4.  
  5. long l[5];
  6. char * c = reinterpret_cast<char*>(l);
  7.  
  8. void print()
  9. {
  10. for (int r = 0; r != sizeof(l)/sizeof(l[0]); ++r)
  11. {
  12. long value = l[r];
  13. const char * bytes = reinterpret_cast<char*>(&value);
  14.  
  15. std::cout << "Array index " << r << ": ";
  16. for (int c = 0; c != sizeof(l[0]); ++c)
  17. {
  18. if (c != 0)
  19. {
  20. std::cout << " ";
  21. }
  22. std::cout << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[c]);
  23. }
  24. std::cout << std::endl;
  25. }
  26. std::cout << std::endl;
  27. }
  28.  
  29. int main()
  30. {
  31. long & aligned = *reinterpret_cast<long*>(&c[0]);
  32. long & misaligned = *reinterpret_cast<long*>(&c[2*sizeof(long) - 1]); // misaligned
  33.  
  34.  
  35. std::cout << "aligned: " << aligned << std::endl;
  36. std::cout << "misaligned: " << misaligned << std::endl;
  37. print();
  38.  
  39. aligned = 1;
  40. misaligned = 2;
  41.  
  42. std::cout << "aligned: " << aligned << std::endl;
  43. std::cout << "misaligned: " << misaligned << std::endl;
  44. print();
  45.  
  46. int n = 0;
  47. short * s = reinterpret_cast<short*>(&n);
  48.  
  49. }
Success #stdin #stdout 0s 2884KB
stdin
Standard input is empty
stdout
aligned: 0
misaligned: 0
Array index 0: 00 00 00 00
Array index 1: 00 00 00 00
Array index 2: 00 00 00 00
Array index 3: 00 00 00 00
Array index 4: 00 00 00 00

aligned: 1
misaligned: 2
Array index 0: 01 00 00 00
Array index 1: 00 00 00 02
Array index 2: 00 00 00 00
Array index 3: 00 00 00 00
Array index 4: 00 00 00 00