我正在 Rust 中尝试原始指针。我有以下代码:
fn main() {
let mut t: u8 = 0;
let addr = &mut t as *mut u8 as usize;
let x = addr as *mut [bool; 8];
let y = addr as *mut u8;
unsafe {
*y = 0b10101010;
println!("{:?} {:b}", *x, *y);
}
}
Run Code Online (Sandbox Code Playgroud)
它产生以下输出:[true, true, true, true, true, true, true, false] 10101010
虽然我希望它打印[true, false, true, false, true, false, true, false] 10101010. 到底是怎么回事?bool数组不是按位存储的吗?
该程序的行为未定义(因此输出毫无意义)。从美里出发:
error: Undefined Behavior: memory access failed: pointer must be in-bounds at offset 8, but is outside bounds of alloc1381 which has size 1
--> src/main.rs:11:31
|
11 | println!("{:?} {:b}", *x, *y);
| ^^ memory access failed: pointer must be in-bounds at offset 8, but is outside bounds of alloc1381 which has size 1
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
Run Code Online (Sandbox Code Playgroud)
布尔数组是按字节存储的,而不是按位存储的。如果您想要逐位存储,请使用bitvec或crate。bitfield指针无法指向单个位:指针始终指向字节(基本上任何 ISA 都不支持指向位的指针)。bools 的长度为 1 个字节,不能安全地使用0_u8或 以外的任何值1_u8。
| 归档时间: |
|
| 查看次数: |
909 次 |
| 最近记录: |