I’m working in a code that has a data structure like this:
type
TData1 = record
IntField: Integer;
StrField: string;
end;
TData2 = record
DateField: TDateTime;
StrField: string;
end;
var
AData1 = array of ^TData1;
AData2 = array of ^TData2;
Sometimes I have to add an element to one of that arrays, like this:
L := Length(AData1);
SetLength(AData1, L + 1);
New(AData1[L]);
How can I write a procedure that does that job of increasing the array size and allocating memory for a new item that works for any kind of pointer? And it must be done without changing the definitions of the records (TData1, TData2) and the arrays (AData1, AData2), so it won’t break existing code.
Ps: I don’t have much background with pointers and that kind of programming, I’d certainly use objects and dynamic linked lists, but in this case it’s a legacy code and I can’t change it, at least for now.
Update:
This is not a full answer.UsingTDynArrayas mentioned by David may solve your problem.Using RTTI I made a another solution for you. It is a generic solution and you can easily add more functions/capabilities. It will preserve your type declarations. Example of adding/removing records is included.
The record
TDynPtArrayhandles any dynamic array of pointers to records. It is initialized with anInitcall:–
And a little test: