I want to create an array, but its size depends on how many records a file has. So i want to READ a file and after counting how many records it has i want to initialize that array. What's the best way to do this?
Use an array based on a pointer, load the array from the file then allocate the right size of the array to the pointer. That is :
PHP Code:
D MyArray DS
Dim(9999) Based(p_My Array)
p_MyArray = Alloc(Size(Myarray) * 9999);
// Load the array from the file
Do U EOF();
Read File ...
...
// Count # of entries
MyArray_Cnt += 1;
// Loop
End do;
// Reallocate the size of the array
p_MyArray = %Realloc(p_MyArray : %size(MyArray) * MyArray_Cnt);
...
// End of Program
Dealloc p_MyArray;
InLR = *On;
1/ Example WITHOUT qualified
PHP Code:
D Arr ds Based(p_Arr) D ArrEntry 10a Dim(999) D ArrFld1 3a Overlay( ArrEntry : *Next )D ArrFld2 7a Overlay( ArrEntry : *Next )
...D ArrCnt s 10i 0 inz
/free
p_Arr = %Alloc(%Size(ArrEntry) * 9999);
// Load the array from the file
Do U EOF();
Read File ...
If EOF();
Leave;
Else
// Count # of entries
ArrCnt = +1;
// Load the array
ArrFld1(ArrCnt) = Fld1;
ArrFld2(ArrCnt) = Fld2;
...
End If;
End do;
p_Arr = %Realloc(p_Arr : %size(ArrEntry) * ArrCnt);
// Reallocate the size of the array
...
// End of Program
Dealloc p_Arr;
*inlr = *on;
2/ Example WITH qualified
PHP Code:
D Arr_Template ds Qualified
D Fld1 ... D Fld2 ...
... D Arr ds Based(p_Arr) D Dim(9999) D Likeds(Arr_Template)
D ArrCnt s 10i 0 inz
/free
p_Arr = %Alloc(%Size(Arr) * 9999);
Do U EOF();
Read File ...
If EOF();
Leave;
Else
// Count # of entries
ArrCnt += 1;
// Load the array
Arr(ArrCnt).Fld1 = Fld1;
Arr(ArrCnt).Fld2 = Fld2;
...
End If;
End Do;
p_Arr = %Realloc(p_Arr : %size(Arr) * ArrCnt);
// Reallocate the size of the array
...
// End of Program
Dealloc p_Arr;
*inlr = *on;
No comments:
Post a Comment