John Boe
John Boe

Reputation: 3621

How to allocate memory to pointer to a record? Delphi 7

I have this type:

type
  pTRegex_sec=^TRegex_sec;
  TRegex_sec = record
  secs: Array of pTRegex_sec;
  len: byte;
  hasSections: boolean;
  hasUnits: boolean;
  units: Array of TRegex_unit;
end;

type TRegex_assertions = record
  len: byte;
  secs: Array of TRegex_sec;
end;

I would like to allocate memory for the type TRegex_sec:

var Assertions: TRegex_assertions;
begin
  setlength(Assertions.secs, 1);
  GetMem(Assertions.secs[0], SizeOf(TRegex_sec));
end;

The error I have is "Incompatible types": Assertions.secs[0]<-- here

Another attempt, same error:

New(Assertions.secs[0]);

How to do it correctly?

Upvotes: 1

Views: 980

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597896

The TRegex_assertions.secs field is a dynamic array of records, not an array of pointers. There is no need to use GetMem() to allocate that array, SetLength() already handles that for you.

However, the TRegex_sec.secs field is a dynamic array of pointers. Use SetLength() to allocate that array as needed, and then use New() to allocate individual TRegex_sec instances to populate it with:

var
  Assertions: TRegex_assertions;
begin
  SetLength(Assertions.secs, 1);
  SetLength(Assertions.secs[0].secs, 1);
  New(Assertions.secs[0].secs[0]);
  ... 
end;

Upvotes: 3

Related Questions