判断一个数组的长度用 Length 还是 SizeOf ?
最近发现一些代码, 甚至有一些专家代码, 在遍历数组时所用的数组长度竟然是 SizeOf(arr); 这不合适!
如果是一维数组、且元素大小是一个字节, 这样用看不出错误, 譬如:
--------------------------------------------------------------------------------
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)]);
{显示结果: 10,10,10,10}
end;
--------------------------------------------------------------------------------
但如果数组元素多于一个字节、或是多维数组的情况下, 就不行了, 举例:
--------------------------------------------------------------------------------
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;
--------------------------------------------------------------------------------
我们倒是可以利用这个原理, 迅速知道多维数组的元素总数:
--------------------------------------------------------------------------------
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(SizeOf(arr) div SizeOf(Integer))); {24}
end;