Creating an array alias

by Richard Russell, June 2009, modified August 2020

If you use a simple array assignment statement to copy an array the contents are copied (that is, each element of the source array is copied into the destination array):

      destarray() = srcarray()

For this to work the destination array must first have been created (using DIM) and must have the same number of elements (of the same type) as the source array.

As an alternative to copying the contents of an array, you can create an array alias, i.e. another name for the same array. You can do that as follows:

      PROCsetarrayptr(aliasarray(), FNgetarrayptr(srcarray()))
      DEF FNgetarrayptr(RETURN a%%) = a%%
      DEF PROCsetarrayptr(RETURN a%%, p%%) : a%% = p%% : ENDPROC

Once this code has been executed aliasarray() refers to the same array as srcarray() - it has the same dimensions and the same contents. Any changes you make to one array will affect the other array. The alias array need not have been first created using DIM (and indeed it's better if it isn't, to avoid a memory leak).

You may well ask why you would ever want to do such a seemingly strange thing. One reason is to make an array which has been passed into a procedure (or a function) available globally. Consider the following code example:

        DEF PROCusearray(text$())
        REM code omitted here...
        PROCsetarrayptr(GlobalText$(), FNgetarrayptr(text$()))
        REM code omitted here...
        ENDPROC

The array text$() is a formal parameter of the procedure PROCusearray. Therefore its scope is limited to code within (or called from) that procedure; once the ENDPROC has been executed the array text$() is no longer accessible. Suppose the procedure sets up an interrupt (e.g. ON TIME), and the interrupt service routine needs to access the contents of the array (even after the ENDPROC has been executed). One way to achieve that is to create a global alias of the array (GlobalText$() in the example above); this remains accessible even after the procedure has been exited.

Of course the interrupt service routine could have accessed the actual parameter of the procedure (the array passed in the call to PROCusearray) but that goes contrary to the principle of information hiding whereby a procedure or function (which might for example be in a library) shouldn't need to know the names of variables, arrays, structures etc. in the code from which it is called. There's also no guarantee that the actual parameter is itself globally accessible (it could be LOCAL to another procedure/function from which PROCusearray was called).