Pointer math in C vs pointer math in Delphi

Viewed 160

I have to rewrite following C code to Delphi:

register short* p;
short k;
int i;

k = p[i];

The result looks so:

{$POINTERMATH ON}
var
  p: ^SmallInt;
  k: SmallInt;
  i: Integer;
begin
  k := p[i];
end;

Now I am a bit unsure about pointer math used here.

Does p[i] mean that p is taken and then advanced for i bytes?

Or may be p is taken and then advanced for i 16-bit words?

Also I'm unsure about Delphi pointer math syntax. Logically p[i] in Delphi code should look for me like p[i]^, but the last variant produces a compiler error "E2017 Pointer type required".

Is my code conversion attempt correct?

1 Answers

Note that I will use i instead of d1str + d1st1 as indices in the answer below because it makes the exposition clearer. Once you understand it in this simpler form, it will be easier to understand the actual code.

Does p[i] mean that p is taken and then advanced for i bytes?

No. It means, that p is treated as a pointer to an array of short. And then p[i] is the i-th element of that array.

p[i] in Delphi code should look for me like p[i]^

No. p[i] is an expression of type short. That's not a pointer, so you can't apply ^ to it.

Is my code conversion attempt correct?

Yes.

Related