关于数组的一个问题

字体大小: 中小 标准 ->行高大小: 标准
我们知道,在Delphi中有一个Type的Byte Array!这个有什么用呢?其实这个可以作为动态数组来使用,例如,我们可以Type一个尽可能大的数组:

Type

TMyByteArray=array[0..32767] of integer; ////也可以使用记录!

PMyByteArray=^TMyByteArray;

不用担心内存的问题,是用Type定义数组的时候,是没有分配内存的,需要到变量的时候才会分配内存,因此,我们定义变量的时候,应该使用指针!

var

Demo:PMyByteArray;

使用的时候,可以使用GetMem来申请内存:

GetMem(Demo,500*SizeOf(integer)); ///这样,Demo就有500个数组元素了

以后就可以使用了。:)

下面给出一些编写好的通用的例程:

Procedure AllocArray( Var pArr: Pointer; items, itemsize: Cardinal;

Var maxIndex: Cardinal);

Begin

If items > 0 Then Begin

GetMem( pArr, items * itemsize);

maxIndex := Pred( items );

End

Else Begin

pArr := Nil;

maxIndex := 0; { WARNING! This is still an invalid index here! }

End;

End;

Procedure ReDimArray( Var pArr: Pointer; newItems, itemsize: Cardinal;

Var maxIndex: Cardinal );

Begin

If pArr = Nil Then

AllocArray( pArr, newItems, itemsize, maxIndex )

Else Begin

ReAllocMem( pArr, Succ(maxIndex)*itemsize,

newItems*itemsize);

maxIndex := Pred( newItems );

End;

End;

Procedure DisposeArray( Var pArr: Pointer; itemsize, maxIndex: Cardinal );

Begin

FreeMem( pArr, Succ(maxIndex)*itemsize);

End;

调用示例如下:

type

{we can directly declare a pointer to an array, no need to declare

the array first}

PDoubleArray = ^Array [0..High(Cardinal) div Sizeof(Double) -1] of

Double;

Var

pDbl: PDoubleArray;

maxIndex, i: Cardinal;

deg2arc: Double;

Begin

deg2arc := Pi/180.0;

try

AllocArray( pDbl, 360, Sizeof( Double ), maxIndex );

For i:= 0 To maxIndex Do

pDbl^[i] := Sin( Float(i) * deg2arc );

ReDimArray( pDlb, 720, Sizeof( Double ), maxIndex );

For i:= 360 To maxIndex Do

pDbl^[i] := Cos( Float(i-360) * deg2arc );

finally

DisposeArray( pDbl, Sizeof(Double), maxIndex );

end;

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/67881.html