关于数组的一个问题

I

import

Unregistered / Unconfirmed
GUEST, unregistred user!
我们知道,在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^ := Sin( Float(i) * deg2arc );
ReDimArray( pDlb, 720, Sizeof( Double ), maxIndex );
For i:= 360 To maxIndex Do
pDbl^ := Cos( Float(i-360) * deg2arc );
finally
DisposeArray( pDbl, Sizeof(Double), maxIndex );
end;
 

Similar threads

I
回复
0
查看
379
import
I
S
回复
0
查看
947
SUNSTONE的Delphi笔记
S
S
回复
0
查看
768
SUNSTONE的Delphi笔记
S
顶部