gpt4 book ai didi

pointers - 将指针的值存储在 Rust 中的另一个指针中

转载 作者:行者123 更新时间:2023-11-29 08:11:21 26 4
gpt4 key购买 nike

将一个指针存储为另一个指针的值的最佳方法是什么?

我有一个类型为*mut u8 的变量ptr。如何将 ptr 指向的地址存储为另一个指针 t 的值,该指针也是 *mut u8 类型。

我正在尝试做类似的事情

*t = ptr;

我收到 expected u8, found *-ptr 错误。我知道地址 ptr 是 64 位的。我想从地址 t 开始填充 64 位。

最佳答案

I have a variable ptr that is of type *mut u8. How do I store the address that the ptr points to as the value of another pointer t that is also of type *mut u8

将一个指针分配给另一个指针:

use std::ptr;

fn main() {
let ptr: *mut u8 = ptr::null_mut();
let t: *mut u8 = ptr;
}

ptr 是一个指针,它指向的地址是NULL。此值现在存储在与 ptr 相同类型的指针 t 中:t 指向地址 NULL .

+-----+        +-----+
| | | |
| ptr | | t |
| | | |
+--+--+ +--+--+
| |
| |
+---->NULL<----+

如果您想让 t 成为指向另一个指针的地址 的指针,您需要引用 ptr。类型也不能相同:

use std::ptr;

fn main() {
let ptr: *mut u8 = ptr::null_mut();
let t: *const *mut u8 = &ptr;
}
+-----+      +-----+
| | | |
| t +------> ptr +----->NULL
| | | |
+-----+ +-----+

I am looking for a way to write the address that the ptr points to to a specific location so that I can get the address even when I don't have t

原始指针没有与之关联的编译器强制生命周期。如果你想在值消失后保留某物的地址,这对他们来说是一个理想的情况——你不需要做任何事情:

use std::ptr;

fn do_not_dereference_this_result() -> *const u8 {
let val: u8 = 127;
let ptr: *const u8 = &val;
ptr
}

fn main() {
println!("{:p}", do_not_dereference_this_result())
}

在极少数情况下,您可能希望将地址存储在 usize(指针大小的整数值)中:

use std::ptr;

fn do_not_dereference_this_result() -> usize {
let val: u8 = 127;
let ptr: *const u8 = &val;
ptr as usize
}

fn main() {
println!("{:x}", do_not_dereference_this_result())
}

真的听起来您对指针的工作原理感到困惑,这是一个很好的迹象,表明如果您使用它们,您将搬起石头砸自己的脚。我强烈鼓励您在任何重要代码中只使用引用,直到您对指针的理解有所增加。

关于pointers - 将指针的值存储在 Rust 中的另一个指针中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49143327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com