fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <iomanip>
  4. #include <cstring>
  5. using namespace std;
  6.  
  7. bool is_aligned (char *p) {
  8. return reinterpret_cast<unsigned long long>(p)%alignof(int)==0;
  9. }
  10. void dump(const string &message, char *p, size_t s) {
  11. cout << message << hex;
  12. for (int i=0; i<s; i++) cout<< (int) p[i]<<" "; cout<<endl;
  13. cout<<dec;
  14. }
  15.  
  16. int main() {
  17. int x = 27;
  18. char w;
  19. char z [sizeof(int)*10+1];
  20. char y;
  21.  
  22. // check conditions
  23.  
  24. cout << " "<< alignof(x) << " "<< alignof(y) << " "<< alignof(z)<<endl;
  25. cout << " "<< &x << " "<< (void*)&y << " "<< (void*) z<<endl;
  26. char *p = z + is_aligned(z); // never aligned unless int is aligned on 1
  27. cout << "Is z aligned for int ? " << (is_aligned(z) ?"yes":"no") <<endl;
  28. cout << "Is p aligned for int ? " << (is_aligned(p) ?"yes":"no") <<endl;
  29.  
  30. // memcpy option
  31. memcpy (p, &x, sizeof(x)); // test
  32. dump ("Int stored with memcpy: ", p, sizeof(int));
  33. x=0;
  34. memcpy (&x,p, sizeof(x));
  35. memset(p, 0, sizeof (x));
  36. cout << "restored: "<<x<<endl;
  37.  
  38. // reinterpret cast option:
  39. cout << "Going to store with reinterpret cast."<<endl;
  40. *reinterpret_cast<int*>(p) = x; //ouch
  41. dump ("Int stored with reinterpret cast: ", p, sizeof(int));
  42. x=0;
  43. cout << "Going to restore with reinterpret cast."<<endl;
  44. x = *reinterpret_cast<int const*>( p );
  45. cout << "restored: "<<x<<endl;
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
 4 1 1
 0x7ffc5f25455c 0x7ffc5f25455b 0x7ffc5f254580
Is z aligned for int ? yes
Is p aligned for int ? no
Int stored with memcpy: 1b 0 0 0 
restored: 27
Going to store with reinterpret cast.
Int stored with reinterpret cast: 1b 0 0 0 
Going to restore with reinterpret cast.
restored: 27