စံကား

08Pointers and the heap

Changing the caller's variables

Pass addresses to a function so it can change the caller's variables.

A parameter is a duplicate, so a function cannot change the variable passed in. Pass the variable's address instead. The function then writes through the pointer, and the change reaches the caller's variable.

စံကား

Expected output

၂
၁
ZakaReads as
ငှားထားသော ကိန်းပြည့် လိပ်စာ ကa parameter က that borrows an integer: the caller keeps the variable
ပထမ ၏ လိပ်စာ"the address of the first", passed as an argument
ယာယီ"short-lived"

Several results

A function returns at most one result. Pointers let it hand back more: the caller passes the addresses of the variables that should receive them.

စံကား

Expected output

၃
၂

5 goes into 17 three times, with 2 left over.

How long an address lasts

The variables of a function end with the call: when it returns, their RAM is given back. So a borrow of one of them must not leave the function, and the compiler refuses a result that would take it out:

စံကားZK0706

Expected error

error[ZK0706]: returns a borrow of the local "x", which ends when the function returns

Pointing into a function at the caller's variables, as လဲလှယ် does, is fine in all cases: the caller's variables outlive the call. RAM that must outlive the function that creates it is a block from the heap, and the function hands its caller the owner of that block; see ownership and borrowing.

Hands on

  • Write a function that takes the addresses of three integers and sorts their values from smallest to largest, using လဲလှယ်.
  • Call လဲလှယ် with the same address twice: ပထမ ၏ လိပ်စာ၊ ပထမ ၏ လိပ်စာ. What happens, and what is the reason?

Next: The heap.