Misunderstanding with pointer and parameters


#1

I have written small code. I surely know that I have a misunderstanding in the usage of pointer:

fn div(a : & u32, b : &u32, c : &u32) {
    let mut temp = *a;
    *c = 0;
    while temp > *b {
        temp = temp - *b;
        *c = *c + 1;
    }
}

fn main() {
    let a : u32 = 50;
    let b : u32 = 3;
    let mut result : u32 = 0;
    div(&a,&b,&result);
    println!("The result of a / b is {}", result);
}

The Compiler says:

Cargo-Process started at Thu Dec 22 20:05:25

cargo build
   Compiling list v0.1.0 (file:///home/ahmed/list)
error: cannot assign to immutable borrowed content `*c`
 --> main.rs:3:5
  |
3 |     *c = 0;
  |     ^^^^^^

error: cannot assign to immutable borrowed content `*c`
 --> main.rs:6:9
  |
6 |         *c = *c + 1;
  |         ^^^^^^^^^^^

error: aborting due to 2 previous errors

error: Could not compile `list`.

To learn more, run the command again with --verbose.

Cargo-Process exited abnormally with code 101 at Thu Dec 22 20:05:25

Can someone please explain me what I have done wrong?


#2

You’ve done almost everything right!

You correctly dereference a and b with *a and *b. However, c is a reference as well, and you need to deference it on both side of the assignment: *c = *c + 1.

Now, rustc would complain that you mutate c though a constant reference. To fix it, change the div signature to fn div(a : & u32, b : &u32, c : &mut u32) and the call site to div(&a,&b,&mut result);.


#3

Thanks Sir for your help. I am learning right now. You have helped me much!

Greetz

Ahmed