determine the length of an array using length or SizeOf?
recently found some code, and even some expert code, the length of the array used to traverse the array is SizeOf (arr); this is inappropriate!
if it is a one-dimensional array, and the element size is a byte, it does not see the error, for example:
--------------------------------------------------------------------------------
var
arr1:array[0..9] of Char;
arr2:array[0..9] of Byte;
begin
showmessagefmt ('%d,%d,%d,%d ', [Length (ARR1), SizeOf (arr1),
Length (ARR2), SizeOf (ARR2)]);
{display result: 10,10,10,10}
end;
--------------------------------------------------------------------------------
but if the array element is more than one byte, or a multidimensional array, it is not, for example:
--------------------------------------------------------------------------------
Const
ARR1:ARRAY[0..9] of Integer = (1,2,3,4,5,6,7,8,9,10);
Arr2:array[0..1, 0..3] of Integer = ((1,2,3,4), (5,6,7,8));
Var
Arr3:array[boolean] of Integer;
Arr4:array[byte] of Integer;
Begin
ShowMessage (IntToStr (Length (ARR1))); {10}
ShowMessage (IntToStr (SizeOf (ARR1))); {40}
ShowMessage (IntToStr (Length (ARR2))); {2}
ShowMessage (IntToStr (Length (arr2[0))); {4}
ShowMessage (IntToStr (Length (arr2[1))); {4}
ShowMessage (IntToStr (SizeOf (ARR2))); {32}
ShowMessage (IntToStr (Length (ARR3))); {2}
ShowMessage (IntToStr (SizeOf (ARR3))); {8}
ShowMessage (IntToStr (Length (ARR4))); {256}
ShowMessage (IntToStr (SizeOf (ARR4))); {1024}
End
--------------------------------------------------------------------------------
We can use this principle to quickly know the total number of elements in a multidimensional array:
--------------------------------------------------------------------------------
Const
Arr:array[0..1, 0..2, 0..3] of Integer =
((1,1,1,1), (2,2,2,2), (3,3,3,3)), ((4,4,4,4), (5,5,5,5), (6,6,6,6)));
Begin
ShowMessage (IntToStr (arr) div sizeof (Integer))); {24}
End
Does Delphi judge the length of an array with lengths or SizeOf?