How do I make the equivalent of a C double pointer

2020-01-20 13:00发布

I started porting C code to Rust, but I'm confused about how things work in Rust. What is the equivalent of this code:

typedef struct Room {
    int xPos;
    int yPos;
} Room;

void main (){
  Room **rooms;
  rooms = malloc(sizeof(Room)*8);
}

标签: pointers rust
1条回答
smile是对你的礼貌
2楼-- · 2020-01-20 13:08

What is the equivalent of this code

Assuming you mean "a collection of Rooms with capacity for 8":

struct Room {
    x_pos: i32,
    y_pos: i32,
}

fn main() {
    let rooms: Vec<Room> = Vec::with_capacity(8);
}

It's exceedingly rare to call the allocator directly in Rust. Generally, you have a collection that does that for you. You also don't usually explicitly specify the item type of the collection because it can be inferred by what you put in it, but since your code doesn't use rooms at all, we have to inform the compiler.

As pointed out in the comments, you don't need a double pointer. This is the equivalent of a Room *. If you really wanted an additional level of indirection, you could add Box:

let rooms: Vec<Box<Room>> = Vec::with_capacity(8);

How do I make the equivalent of a C double pointer

One of the benefits of Rust vs C is that in C, you don't know the semantics of a foo_t **. Who should free each of the pointers? Which pointers are mutable? You can create raw pointers in Rust, but even that requires specifying mutability. This is almost never what you want:

let rooms: *mut *mut Room;

In certain FFI cases, a C function accepts a foo_t ** because it wants to modify a passed-in pointer. In those cases, something like this is reasonable:

unsafe {
    let mut room: *mut Room = std::ptr::null_mut();
    let room_ptr: *mut *mut Room = &mut room;
}
查看更多
登录 后发表回答