Delphi 6中嵌套For循环初始化错误技术咨询
TNumbers.CleanTable First off, let's break down exactly why that nested For loop is throwing an initialization error—this is a super common pitfall with Delphi's dynamic arrays, especially in older versions like Delphi 6.
Core Root Causes
- Dynamic arrays are 0-indexed in Delphi: Your code starts loops at
1, but Delphi dynamic arrays (which it looks likeCorrespondenceis) start at index0. When your array has fewer than 2 elements, this creates an invalid loop range. - No empty array checks: If
Correspondenceis empty,Length(Correspondence)returns0, makingIEND-1 = -1. A loop likefor Index := 1 to -1is completely invalid and triggers the initialization error immediately. - Unsafe subarray assumption: You're using
Length(Correspondence[0])as the universalJEND, but dynamic 2D arrays can have subarrays of varying lengths. IfCorrespondence[0]is empty, you get the same invalid loop range issue for the inner loop.
Step-by-Step Fixes
Here's how to rewrite your code to eliminate the error and add safety checks:
1. Add Guard Clauses for Empty Arrays
First, exit early if your main array or first subarray is empty to avoid invalid loop ranges:
procedure TNumbers.CleanTable(Sender: TObject); var Index: integer; JIndex: integer; IEND, JEND: integer; Obj: TObject; begin IEND := Length(Correspondence); if IEND = 0 then Exit; // Exit if main array is empty JEND := Length(Correspondence[0]); if JEND = 0 then Exit; // Exit if first subarray is empty // Rest of your code below...
2. Fix Loop Index Ranges
Use Delphi's built-in Low() and High() functions to get the actual valid index range of your arrays—this works for both dynamic and static arrays, making your code more robust:
// Replace your original nested loops with this: for Index := Low(Correspondence) to High(Correspondence) do begin // Check if current subarray exists and isn't empty if (Index < 0) or (Index > High(Correspondence)) then Break; JEND := Length(Correspondence[Index]); if JEND = 0 then Continue; // Skip empty subarrays for JIndex := Low(Correspondence[Index]) to High(Correspondence[Index]) do begin obj := SearchForTagID(Correspondence[Index,JIndex], Sender); if obj = nil then Continue; if obj is TComponent then begin if TComponent(Obj).Tag = Correspondence[Index, JIndex] then begin // Insert your original cleanup logic here (e.g., freeing components, clearing values) end; end; end; end;
3. Handle Variable-Length Subarrays
If your 2D array has subarrays of different lengths, avoid using Correspondence[0]'s length for all inner loops. Instead, get the length of the current subarray in each outer loop iteration (as shown above) to prevent index out-of-bounds errors.
Why This Works
Low()returns the first valid index of the array (0 for dynamic arrays in Delphi 6)High()returns the last valid index (equivalent toLength(Array) - 1)- Guard clauses prevent invalid loop ranges entirely before they can execute
内容的提问来源于stack exchange,提问作者Christian Martin

