user5280366
user5280366

Reputation:

How do I allocate an array at runtime in Rust?

Once I have allocated the array, how do I manually free it? Is pointer arithmetic possible in unsafe mode?

Like in C++:

double *A=new double[1000];
double *p=A;
int i;
for(i=0; i<1000; i++)
{
     *p=(double)i;
      p++;
}
delete[] A;

Is there any equivalent code in Rust?

Upvotes: 12

Views: 25637

Answers (2)

DK.
DK.

Reputation: 59005

Based on your question, I'd recommend reading the Rust Book if you haven't done so already. Idiomatic Rust will almost never involve manually freeing memory.

As for the equivalent to a dynamic array, you want a vector. Unless you're doing something unusual, you should avoid pointer arithmetic in Rust. You can write the above code variously as:

// Pre-allocate space, then fill it.
let mut a = Vec::with_capacity(1000);
for i in 0..1000 {
    a.push(i as f64);
}

// Allocate and initialise, then overwrite
let mut a = vec![0.0f64; 1000];
for i in 0..1000 {
    a[i] = i as f64;
}

// Construct directly from iterator.
let a: Vec<f64> = (0..1000).map(|n| n as f64).collect();

Upvotes: 19

Information Aether
Information Aether

Reputation: 408

It is completely possible to allocate a fixed-sized array on the heap:

let a = Box::new([0.0f64; 1000]);

Because of deref coercion, you can still use this as an array:

for i in 0..1000 {
    a[i] = i as f64;
}

You can manually free it by doing:

std::mem::drop(a);

drop takes ownership of the array, so this is completely safe. As mentioned in the other answer, it is almost never necessary to do this, the box will be freed automatically when it goes out of scope.

Upvotes: 20

Related Questions