Recent

Author Topic: Arithmetics with typed pointers ?  (Read 4282 times)

Nitorami

  • Hero Member
  • *****
  • Posts: 605
Arithmetics with typed pointers ?
« on: April 13, 2015, 10:45:17 am »
I do not quite understand the logic of pointer arithmetics. The example provides the expected result in both cases, but why do I have to multiply in the first version ?

Code: [Select]
const table: array [0..5] of single = (0,1,2,3,4,5);

var p: psingle;
begin
  p := @table + 3 * sizeof (single); //need to multiply by size to make it work
  writeln (p^);

  p := psingle(@table) + 3;
  writeln (p^);
end.

Laksen

  • Hero Member
  • *****
  • Posts: 802
    • J-Software
Re: Arithmetics with typed pointers ?
« Reply #1 on: April 13, 2015, 11:23:12 am »
Who knows? Why would you need such C-ish code? :P

But it's probably because @table is a ^array[0..5] of single instead of a ^single. If you try @table[0] then you might not need the multiplication anymore.

Nitorami

  • Hero Member
  • *****
  • Posts: 605
Re: Arithmetics with typed pointers ?
« Reply #2 on: April 13, 2015, 11:36:00 am »
Quote
Who knows? Why would you need such C-ish code?

Agreed, I do not like this either, but in some cases e.g. when accessing multidimensional arrays, pointer arithmetic can be significantly faster. The compiler is not (yet) smart enough to optimize this, and recalculates the target address on each access.

@table[0] does not change it BTW.

varianus

  • New Member
  • *
  • Posts: 27
Re: Arithmetics with typed pointers ?
« Reply #3 on: April 13, 2015, 11:46:00 am »
IIRC, the @ operator returns a generic pointer. So in the first case you must specify how many bytes the pointer should be incremented to find the 3rd elements.

In the second case, the typecast "tells" to the compiler the size of the element  so, by doing some "compiler magic", it already knows how many bytes to move for every element.

engkin

  • Hero Member
  • *****
  • Posts: 3112
Re: Arithmetics with typed pointers ?
« Reply #4 on: April 13, 2015, 11:51:12 am »
As mentioned by varianus, quoting the docs:
Quote
Free Pascal supports pointer arithmetic as C does. This means that, if P is a typed pointer, the instructions
Inc(P); 
Dec(P);

Will increase, respectively decrease the address the pointer points to with the size of the type P is a pointer to. For example
Var P : ^Longint; 
... 
 Inc (p);

will increase P with 4, because 4 is the size of a longint. If the pointer is untyped, a size of 1 byte is assumed (i.e. as if the pointer were a pointer to a byte: ^byte.)

Nitorami

  • Hero Member
  • *****
  • Posts: 605
Re: Arithmetics with typed pointers ?
« Reply #5 on: April 13, 2015, 12:01:03 pm »
Alright. I had assumed that with

var p: psingle

the compiler should know that p will in fact point to a single. But if the @ operator makes p untyped, that explains it.

 

TinyPortal © 2005-2018