Return to the RPG Tips
Dynamic Arrays with RPG IV
Q. Does RPG have anything comparable to LotusScript's or Visual Basic's REDIM command that lets you redimension an array?
A. RPG IV doesn't directly support arrays with a variable number of elements. You have to handle all the storage allocation yourself, and since you have no way to tell RPG what the new dimension of your array is, you'll have to handle lookup and sort yourself, too. The advantage of using a dynamically allocated array is that you don't have to allocate storage that you aren't going to use. The disadvantage is that your code becomes more complex.
There's an example of managing dynamic arrays in the ILE RPG for AS/400 Programmer's Guide at http://publib.boulder.ibm.com:80/cgi-bin/bookmgr/BOOKS/QB3AGY03/2.5.7.3
The sample code is more complex than what you require, as it also illustrates creating and using your own heap; however, you can skip the create-heap stuff and just use the ALLOC opcode if you want to use the default heap.
Another resource is the April 1997 issue of NEWS/400, which featured an article by Julian Monypenny titled "Dynamic Arrays with RPG IV." The article discusses RPG IV's dynamic memory management, nested copies, and conditional compilation and provides source code for sorting and searching dynamic arrays. AS400 Network professional members can view the article and source code at http://www.as400network.com/article.cfm?ID=1772.
Adapted from a newsgroup answer by IBM Toronto's Barbara Morris
[report a broken link by clicking here]