Using Dynamically-Sized Arrays

If you don't know the number of elements you will need in an array until runtime, you can define the array with the maximum size, and then use a subset of the array in your program.

To do this, you use the %SUBARR built-in function to control which elements are used when you want to work with all the elements of your array in one operation. You can also use the %LOOKUP built-in function to search part of your array.

Figure 81. Example using a dynamically-sized array
 * Define the "names" array as large as you think it could grow
D names           S             25A   VARYING DIM(2000)  
 * Define a variable to keep track of the number of valid elements
D numNames        S             10I 0 INZ(0)  
 * Define another array
D temp            S             50A   DIM(20) 
D p               S             10I 0 
 /free
     // set 3 elements in the names array       
     names(1) = 'Friendly';     
     names(2) = 'Rusty';     
     names(3) = 'Jerome';     
     names(4) = 'Tom';     
     names(5) = 'Jane';     
     numNames = 5;      

     // copy the current names to the temporary array     
     // Note: %subarr could also be used for temp, but     
     //       it would not affect the number of elements     
     //       copied to temp     
     temp = %subarr(names : 1 : numNames);      

     // change one of the temporary values, and then copy     
     // the changed part of the array back to the "names" array     
     temp(3) = 'Jerry';     
     temp(4) = 'Harry';     
     // The number of elements actually assigned will be the     
     // minimum of the number of elements in any array or     
     // subarray in the expression.  In this case, the      
     // available sizes are 2 for the "names" sub-array,     
     // and 18 for the "temp" subarray, from element 3     
     // to the end of the array.     
     %subarr(names : 3 : 2) = %subarr(temp : 3);      
     // sort the "names" array     
     sorta %subarr(names : 1 : numNames); 

     // search the "names" array     
     // Note: %SUBARR is not used with %LOOKUP.  Instead,     
     //       the start element and number of elements     
     //       are specified in the third and fourth     
     //       parameters of %LOOKUP.     
     p = %lookup('Jane' : names : 1 : numNames);


[ Top of Page | Previous Page | Next Page | Contents | Index ]