Jack wrote:
> I thought pointer Delphi was as flexible as pointers in C.
> I just realize that it is not. Or I haven't figured out how
> to use pointers.
>
> In C, I can randomly access any element in a memory block.
> For example, I can do this:
>
> int a[10], *pi, i;
> pi = a;
> for(i = 0; i < sizeof(a); i++)
> printf("%d\n", *(p + i));
That code also demonstrates that you can randomly access any element
*not* in the memory block. That code reads beyond the end of the array.
> Is it possible to access memory in this fashion
>
> *(p + i)
>
> using pointers in Delphi? It seems that it's only possible
> with PChar, but not for pointers for any other data types.
> Is that right?
It's also possible with PWideChar and PAnsiChar. Otherwise, Delphi only
lets you use brackets with things that are actually arrays or pointers
to arrays.
For an arbitrary pointer type PType, the C expression *(p + i)
corresponds to the Delphi expression PType(Cardinal(p) + i * SizeOf(p^)).
You can also define an array pointer type:
type
TTypeArray = array[0..MaxInt div SizeOf(TType) - 1] of TType;
PTypeArray = ^TTypeArray;
Then *(p + i) becomes PTypeArray(p)[i], which is easier to read than the
previous expression I showed, and has the added advantage of accurately
describing what's really going on.
One last thing would be to change the way you walk the memory block:
for (i = 0; i < sizeof a; i++)
printf("%d\n", *p++);
That becomes this Delphi code:
for i := 0 to SizeOf(a) - 1 do begin
writeln(p^);
Inc(p);
end;
Inc and Dec work on all Delphi pointer types (except Pointer), even
though the + and - operators don't.
The preferred thing to do, though, would be to have p be a dynamic array
from the start.
--
Rob
_______________________________________________
Delphi mailing list -> [email protected]
http://www.elists.org/mailman/listinfo/delphi