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:
- We initialize a variable
iwith the value 1. - We call
zeroval(i), which doesn’t change the value ofiinmain. - We call
zeroptr(i), which does change the value ofibecause it modifies the original variable. - Finally, we use the
getaddressfunction to print the memory address ofi.
When you run this script, you’ll see output similar to this:
initial: 1
zeroval: 1
zeroptr: 0
pointer: 140574069478440zeroval 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.