Overlapping data structures are the most needed feature in a program, but they can also be useful when processing APIs or reading multi-format files.
But how do you declare overlapping data structures? Unfortunately, you'll need to use pointers. Fortunately, you won't have to do any pointer manipulation.
To declare a multi-format data structure, you have to declare each data structure independently. This means you declare them as you normally would. For example, Figure 1 contains a data structure named GTIN, and Figure 2 contains a data structure named UPC.
|
Figure 1: GTIN Data Structure
|
Figure 2: UPC Data Structure
At this point, both data structures have their own memory; they are not located in the same memory space. So you have to change them in order to provide a multi-format structure.
The change required is relatively slight; you need to add the BASED keyword to one of the data structures--specifically, to the data structure that is the shorter of the two. This means the UPC data structure would be changed to the following:
D UPC DS Based(pGTIN)
D MerchID 6S 0
D SEQNBR 5S 0
D CHKDIGIT 1S 0
In addition, you need to create the pGTIN pointer that is referenced by the BASED keyword. While declaring this pointer variable isn't strictly required (RPG automatically declares one for you), it is necessary to set this pointer to the address of the GTIN data structure. One way to do that is by explicitly declaring the pointer and initializing it to the address of the GTIN structure:
D pGTIN S * Inz(%Addr(GTIN))
To provide the complete picture, I've reproduced the entire set of statements in Figure 3.
|
Figure 3: Multi-Format Data Structures
Now, these two data structures overlap one another in memory. Actually, the GTIN data structure has its own memory, and the UPC data structure provides access to the GTIN's memory via the pGTIN pointer variable. I've added the QUALIFIED keyword to avoid name collision. If you are still on OS/400 V4, QUALIFIED is not available, so you will need to ensure that the subfield names are unique in each data structure.
The storage for these two data structure would be formatted as illustrated in the following table.
Byte Position | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
GTIN | SeqNbrEx | MerchID | SeqNbr | ChkDigit | ||||||||||
UPC | MerchID | SeqNbr | ChgDigit | | ||||||||||
Data-> | | | | | | | | | | | | | | |
Bob Cozzi has been programming in RPG since 1978. Since then, he has written many articles and several books, including The Modern RPG Language--the most widely used RPG reference manual in the world. Bob is also a very popular speaker at industry events such as RPG World and is the author of his own Web site and of the RPG ToolKit, an add-on library for RPG IV programmers.
LATEST COMMENTS
MC Press Online