pointers - 如果我想在 Rust 中安全地编码,我应该在不使用指针算法的情况下编码吗?

标签 pointers rust pointer-arithmetic

我读过 Rust 中的指针算法可以通过 pointer.offset() 函数完成,但它总是必须在 不安全代码 中实现:

fn main() {
    let buf: [u32; 5] = [1, 2, 3, 4, 5];
    let mut ptr1: *const u32 = buf.as_ptr();
    unsafe {
        let ptr2: *const u32 = buf.as_ptr().offset(buf.len() as isize);
        while ptr1 < ptr2 {
            println!("Address {:?} | Value {}", ptr1, *ptr1);
            ptr1 = ptr1.offset(1);
        }
    }
}

如果我想在 Rust 中安全地编码,我是否应该不使用指针算法而只使用数组的相应索引来编码?还是有其他办法?

最佳答案

If I want to code in Rust securely

那么你不应该使用unsafe不安全 有几个合理的原因(例如,访问已知且可以安全使用的内存位置,例如在微 Controller 上的几个寄存器),但通常您不应该使用它。

should I code without using pointer arithmetic and just using the corresponding index of an array for example

是的。根本没有理由(在这种特定情况下)使用 unsafe 。只需使用

for i in 0..buf.len() {
    println!("Value {}", buf[i]);
}

但是这段代码不被认为是“使用rust 的”,而是使用 for 循环

for i in &buf {
    println!("Value {}", i);
}

关于pointers - 如果我想在 Rust 中安全地编码,我应该在不使用指针算法的情况下编码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55592789/

相关文章:

在 C 中检查 NULL 指针不起作用

performance - 如何使rust代码并行运行更快?

import - 第三方库上的 Rust `unresolved import`

rust - 替代 std::sync::Semaphore 因为它已被弃用?

c - 指针算术 : warning: assignment makes pointer from integer without a cast [enabled by default]

C分数算术

c - 如何在 C 中的结构中包含动态数组?

objective-c - 分配指针 - Objective-C

c - 在对指针到指针数组调用 realloc 以缩小其大小之前是否有必要释放子指针?

java - 如何在 JNA 中向 java 数组添加偏移量