Hm. If I'm reading that code correctly, it looks like bubble sort, but written without using C array indexing (p[i]
) and instead using explicit pointer arithmetic (*(p + i)
). I'm not sure why you'd want to do it that way, but let's talk about it. Specifically, the sort
function.
Formatted, the sort
function reads:
void sort(int *p)
{
int round,t,i;
for(round=1;round<=4;round++)
{
for(i=0;i<=4-round;i++)
if(*(p+i) > *(p+i+1))
{
t=*(p+i); // a[i] *(p+i)
*(p+i)=*(p+i+1);
*(p+i+1)= t;
}
}
}
A mostly-literal translation into Rust, which is not how I would do it, would go something like this:
unsafe fn sort(p: *mut u32) {
for round in 1..=4 {
for i in 0..=4-round {
if *(p.add(i)) > *(p.add(i+1)) {
let t = *(p.add(i)); // a[i] *(p+i)
*(p.add(i)) = *(p.add(i+1));
*(p.add(i+1)) = t;
}
}
}
}
That function is marked unsafe
because it's dealing in raw pointers and performing arbitrary pointer arithmetic, which I think is what you were asking about. (Rust doesn't overload operators like +
for raw pointers, so you use the add
method instead.)
However, it doesn't need to do any of that unsafe stuff. An idiomatic safe Rust implementation would look like this:
fn sort(p: &mut [u32]) { // <-- slice reference instead of raw pointer
for round in 1..p.len() { // <-- adapts to any length of array
for i in 0..p.len() - round {
if p[i] > p[i + 1] { // <-- using indexing instead of pointer arithmetic
p.swap(i, i+1); // <-- slice::swap exchanges two elements
}
}
}
}
Finally, just a warning that your input
routine will process uninitialized memory if fewer than five numbers are provided, which is undefined behavior in both C and Rust. You could avoid this by checking the return code from scanf
and/or initializing your a
array. (Local variables, including arrays, in C are uninitialized unless you explicitly initialize them.)