Inserting an item on a dynamic array of records
Someone asked this question, I had never tried to do this before, but I didn't think it was difficult, here's the answer:
//first, we declare some record that we are going to use
type
TRecord = record
value:string[1];
end;
TMyDynArray = array of TRecord;
{$R *.dfm}
//the function to insert the record
procedure InsertToArray(var theArray:TMyDynArray; const InsertAt:Integer; const value:TRecord; const RecSize:Integer);
var
Len:Integer;
begin
Len:=Length(theArray);
SetLength(theArray, Len+1);
Move(theArray[InsertAt], theArray[InsertAt+1], (Len-InsertAt)*RecSize);
theArray[InsertAt]:=value
end;
//just something to test that the code actually works
procedure TForm1.Button1Click(Sender: TObject);
var
x:TMyDynArray; //here's our array
result:string;
count, RecSize:Integer;
aRecord:TRecord; //the record to be inserted
begin
SetLength(x, 5); //create a new array
x[0].value:='a'; //fill it with some values
x[1].value:='c';
x[2].value:='d';
x[3].value:='e';
x[4].value:='f';
RecSize:=SizeOf(TRecord); //get the size of one TRecord (used in the function to move bytes)
aRecord.value:='b';
InsertToArray(x, 1, aRecord, RecSize); //call our function
//check that it actually worked
result:='';
for count:=0 to Length(x)-1 do
result:=result+x[count].value;
ShowMessage(result)
end;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment