Reputation: 161
I want to populate an array of records, and with my recent exposure to TMappedFile, I am trying to duplicate it, w/o actually using unFileMapping or BlockRead/Write. The purpose is to leave my options open just for that. The problem I am finding is either its not initiating or Create'ing my array correctly.
From what I have seen so far, is that the DataArr
remains nil
after compiling. And causes an memory violation error (0x00000000) which means it's empty/null. My engineer has already addressed to me that the size of the array maybe to large for purpose, and has also mentioned that I am not able to do what I want unless I deference the pointer, ex. DataArr^[0].value1
I believe my confusion lies with SetLength which seems counter intuitive for a Dynamic Array, which is why I commented it out. Otherwise I get an error E2008 incompatible types
.
type
TDataStruct = Record
value1 : array[0..1] of Single;
value2 : array[0..1] of Single;
value3 : array[0..1] of Single;
end;
TDataStructArray = array[0..MaxInt div SizeOf(TDataStruct) - 1] of TDataStruct;
PDataStructArray = ^TDataStructArray;
var
DataArr: PDataStructArray;
begin
//SetLength(DataArr,length(DataArr)+1);
DataArr[0].value1[0] := 2;
Other things that I have tried is used FillChar(DataArr,SizeOf(DataArr),0)
and as well as FillChar(DataArr[0], SizeOf(DataArr[0]) * Length(DataArr));
The following links have been my sources
Upvotes: 1
Views: 10187
Reputation: 34919
A dynamic array is what is says: dynamic.
Dynamic arrays do not have a fixed size or length. Instead, memory for a dynamic array is reallocated when you assign a value to the array or pass it to the SetLength procedure.
Declare
DataArr: Array of TDataStruct;
Use SetLength to allocate records and initialize them at the same time.
SetLength(DataArr,Length(DataArr)+1); // Or preallocate as many as you wish to initialize
Access a record in the array:
DataArr[0].value1[0] := 2;
In your example there is no memory allocation made, hence the error. And SetLength
operates on dynamic arrays, not on pointers to static arrays.
You could manage the pointer with GetMem/FreeMem and initialize with ZeroMem, but that will only cause troubles building and maintaining the code.
Upvotes: 10