//I have a data structure like this
DCL-DS MainDS qualified;
SubField packed(7:0);
Dcl-DS DetailDS dim(100);
detail_1 char(1);
Dcl-DS DetailsofDetails dim(100);
innerField1 packed(10:0);
InnerField2 char(5);
End-Ds;
End-ds;
End-Ds;
I need to read the DS
for count = 1 to %elem(MainDS.DetailDS)
for innercount = 1 to %elem(MainDS.DetailDS(count).DetailsofDetails)
----
//inside logic
endFor;
---
endFor;
My detailsofDetails datastrucure has only 2 elements in it. But still the innercount is going up to the array dimension which is 100. I need the inner loop to go till 2 and not 100.
What am I missing here?
Strictly speaking, using BIF %elem makes sense mainly for working with dynamic arrays (dim(*auto: n) or dim(*var : n)).
But a dynamic array cannot be a structure element.
In your case, as has already been said, it makes sense to obtain counters of actually filled elements of arrays of internal structures.
Something like this
DCL-C MAX_DETAILS 100;
DCL-DS MainDS qualified;
SubField packed(7:0) inz;
DetCount int(5) inz;
Dcl-DS DetailDS dim(MAX_DETAILS);
detail_1 char(1);
DetOfDetCount int(5) inz;
Dcl-DS DetailsofDetails dim(MAX_DETAILS);
innerField1 packed(10:0) inz;
InnerField2 char(5);
End-Ds;
End-ds;
End-Ds;
And then your code will look something like this
for count = 1 to MainDS.DetCount;
for innercount = 1 to MainDS.DetailDS(count).DetOfDetCount;
----
//inside logic
endFor;
---
endFor;
Naturally, when filling arrays, you must update the element counters yourself (and make sure that an "extra" element with an index greater than the array size is not added to the array)
It would also be a good idea to explicitly initialize the structure elements if their type differs from the char type (numeric types and the varchar type).
This is because by default the structure in RPG is identical to a string and will be filled with spaces during initialization. And if you try to access a numeric element of the structure before you assign it a value, you will get a "decimal data error" exception.
In the case of explicit initialization of a numeric field, this will not happen - it will be initialized correctly.