Pointers in Scilab

Scilab supports pointers, allowing you to pass references to values and variables within your program.

function zeroval(ival)
    ival = 0
endfunction

function zeroptr(iptr)
    iptr($) = 0
endfunction

function main()
    i = 1
    disp("initial: " + string(i))

    zeroval(i)
    disp("zeroval: " + string(i))

    zeroptr(i)
    disp("zeroptr: " + string(i))

    disp("pointer: " + string(getaddress(i)))
endfunction

main()

We’ll show how pointers work in contrast to values with two functions: zeroval and zeroptr. zeroval has a scalar parameter, so arguments will be passed to it by value. zeroval will get a copy of ival distinct from the one in the calling function.

zeroptr in contrast takes a reference to a variable. In Scilab, we can simulate this by passing a variable and modifying its last element using iptr($). This approach changes the value of the original variable.

The main function demonstrates the use of these functions:

  1. We initialize a variable i with the value 1.
  2. We call zeroval(i), which doesn’t change the value of i in main.
  3. We call zeroptr(i), which does change the value of i because it modifies the original variable.
  4. Finally, we use the getaddress function to print the memory address of i.

When you run this script, you’ll see output similar to this:

initial: 1
zeroval: 1
zeroptr: 0
pointer: 140574069478440

zeroval doesn’t change the i in main, but zeroptr does because it has a reference to the original variable.

Note that Scilab doesn’t have true pointers like some lower-level languages, but we can simulate similar behavior using references and the getaddress function for demonstration purposes.