fork download
  1. use std::mem;
  2.  
  3. fn main() {
  4. const N: usize = 32;
  5. const BIG: usize = N + 1;
  6.  
  7. // Local array on the stack
  8. let big = [0u8; BIG];
  9.  
  10. // Base address of the large array
  11. let base = big.as_ptr() as usize;
  12. println!(
  13. "base addr: {:#x}, base % align_of::<usize>() = {}",
  14. base,
  15. base % mem::align_of::<usize>()
  16. );
  17.  
  18. // Take a pointer to big[1] and reinterpret it as &[u8; N]
  19. let arr_ptr = unsafe { big.as_ptr().add(1) as *const [u8; N] };
  20. let arr_addr = arr_ptr as usize;
  21. let aligned = arr_addr % mem::align_of::<usize>() == 0;
  22.  
  23. println!(
  24. "arr addr: {:#x}, aligned_to_usize = {}",
  25. arr_addr,
  26. aligned
  27. );
  28.  
  29. // Optional: actually create a reference to the array
  30. let _arr_ref: &[u8; N] = unsafe { &*arr_ptr };
  31.  
  32. println!("align_of::<[u8; N]>() = {}", mem::align_of::<[u8; N]>());
  33. println!("align_of::<usize>() = {}", mem::align_of::<usize>());
  34. }
  35.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
base addr: 0x7ffc471dd2f0, base % align_of::<usize>() = 0
arr addr:  0x7ffc471dd2f1, aligned_to_usize = false
align_of::<[u8; N]>()   = 1
align_of::<usize>()     = 8