I couldn't find a simple thing on google. How to convert a simple Rust array to a pointer?
How to get pointer to [u8; 3]? I tried doing as *mut u8 but it wouldn't work.
Use as_ptr() or as_mut_ptr().
fn main() {
let a: [u8; 3] = [1, 2, 3];
println!("{:p}", a.as_ptr());
}
0x7ffc97350edd
Arrays coerce to slices, so any slice method may be called on an array.
Note that arrays in Rust are just blobs of memory. They does not point on some stored objects, like an arrays in C do, they are a sequence of objects.
If you have some data and want to get a pointer to it, you'll usually create a reference instead, since only references (and other pointers) can be cast to pointers with as:
fn main() {
let a: [u8; 3] = [1, 2, 3]; // a blob of data on the stack...
let a_ref = &a; // a shared reference to this data...
let a_ptr = a_ref as *const u8; // and a pointer, created from the reference
println!("{:p}", a_ptr);
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With