Link to home
Start Free TrialLog in
Avatar of bnz
bnz

asked on

Pointer typecast

Can anybody tell me why the pointer typecast below is necessary.
AllocMem returns a pointer so the typecast is pointless the way I see it, but if it's omitted it crashes.

type
  TMyRec = record
    ip: string[15];
    port: integer;
  end;
var
  MyAry: array of TMyRec;
begin
  //         ||
  //         ||
  //         \/    
  MyAry := Pointer( AllocMem(SizeOf(TMyRec)*2) );
  MyAry[0].ip := '0.0.0.0';
  MyAry[1].ip := '255.255.255.255';
  showmessage(MyAry[0].ip);
  showmessage(MyAry[1].ip);
end;
Avatar of robert_marquardt
robert_marquardt

Why don't you use SetLength?
Uah! The pointer typecast is not necessary, in fact it's plain and simply *wrong*!!!

You can't assign an allocated memory block to a dynamic array. Instead you HAVE to use SetLength (as Robert already said).

Regards, Madshi.
The reason is that dynamic arrays are more than just a simply memory buffer. They have a reference count and such stuff. Just like dynamic strings. You wouldn't do the following, either, or would you?

var str : string;
begin
  str := pointer(AllocMem(100));   // crash code
Avatar of bnz

ASKER

>You wouldn't do the following, either, or would you?
>
>var str : string;
>begin
> str := pointer(AllocMem(100));   // crash code

Heh, I think I would ;)


isn't a string just a simple nullterminated pointer ?

var
    s: string;
begin
    s := 'delphi';
showmessage(s);
end;

if I open the cpu window and look at what it points to it is delphi#0


If the array is wrong, why does it then works ?
ASKER CERTIFIED SOLUTION
Avatar of Madshi
Madshi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
To add to Madshi: A string in Delphi is much more a class in the C++ sense than anything else.
Declaring a string variable implies calling the constructor.
For a Delphi string this is simply assigning nil. nil serves as '' string (empty string).
Any string variable is placed inside a try finally block.
In the finally part the reference counter is decremented and the memory is freed if the counter reaches zero.
Avatar of bnz

ASKER

Thank you both

I have put a follow up question here

https://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=delphi&qid=20274342