How can I reserve memory for a pointer to an array in Delphi?
I am developing a class to represent a special kind of matrix:
type
DifRecord = record
Field: String;
Number: Byte;
Value: smallint;
end;
type
TData = array of array of MainModule.DataRecord;
type
TDifference = array of DifRecord;
type
TFogelMatrix = class
private
M: Byte;
N: Byte;
Data: ^TData;
DifVector: ^TDifference;
procedure init();
public
constructor Create(Rows, Cols: Byte);
destructor Destroy;
end;
Now, in the constructor, I need to reserve memory for the Data and DifVector class members. As I understand it, I am using pointers to an array of records. So the main question is: how can I properly allocate memory? I suppose I cannot use something like this:
because I lose the main idea - to reserve memory space as much as I want at runtime. Thanks for the comments.new(Data);
new(DifVector);
Since you are using dynamic arrays, array of
then you must use SetLength to specify the length of the array that can be dynamically performed.
t. for example:
SetLength(Data, 100);
This won't hold 100 bytes, but will reserve enough space to store 100 elements of whatever type is stored in the array.
Change your declarations for arrays to simple arrays:
Data: TData;
DifVector: TDifference;
and use it with SetLength, it should do the trick.
Also note that in Delphi, variables of dynamic array type are stored as a pointer (in DotNet-talk, you call this a reference type).
If you don't point this variable to a pointer, the compiler won't let you do the allocation yourself. You have to use SetLength (), as already mentioned, lassevk.
With a multidimensional array (like TData), you can set both dimensions in one go by setting all dimensions with a single call to SetLength (). This results in a cubic structure (each dimension is of equal length). But you can also give each index within a dimension a different length for its next dimension. In two dimensions, this is sometimes referred to as a "jagged" array.
To do this, you must write it like this:
SetLength(Data, SizeOfFirstDimension);
for i = 0 to SizeOfFirstDimension - 1 do
SetLength(Data[i], SizeOfSecondDimensionPerIndex(i));
In this example, I use a function called "SizeOfSecondDimensionPerIndex" to determine the size of each array in the second dimension, but you can determine this size in any way you want.
As a side note, I would suggest using the "R" prefix to define the post type. I know this is not in any of the basic coding tutorials, but if you look at "P'-prefixes for pointers", "I-prefixes for interfaces", "F" -prefixes for class fields, "a'-prefixes" for arguments "C'-prefixes for constants", S-prefixes for resourcestring, you can follow this logic and use "R'-prefix for entries". I know this helped me understand my code better!
Good luck!