为什么不将指向 u8 的原始指针转换为指向 8 个布尔值数组的原始指针打印出正确的结果?
Why doesn't converting a raw pointer to a u8 into a raw pointer to an array of 8 booleans print the right result?
我正在 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);
}
}
它产生以下输出:[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
布尔数组是逐字节存储的,而不是逐位存储的。如果您想要逐位存储,请使用 bitvec
or bitfield
crate。指针无法指向单个位:指针始终指向字节(基本上任何 ISA 都不支持指向位的指针)。 bool
s 是 1 个字节长,并且不能安全地具有除 0_u8
或 1_u8
.
以外的任何值
我正在 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);
}
}
它产生以下输出:[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
布尔数组是逐字节存储的,而不是逐位存储的。如果您想要逐位存储,请使用 bitvec
or bitfield
crate。指针无法指向单个位:指针始终指向字节(基本上任何 ISA 都不支持指向位的指针)。 bool
s 是 1 个字节长,并且不能安全地具有除 0_u8
或 1_u8
.