How ptr arithmitic works??? It doesn't make any sense....

rempas rempas at tutanota.com
Mon Dec 5 15:08:41 UTC 2022


On Monday, 5 December 2022 at 08:21:44 UTC, bauss wrote:
>
> Because it's much easier to work with.
>
> Ex. if you have an array of 4 signed 32 bit integers that 
> you're pointing to then you can simply just increment the 
> pointer by 1.
>
> If it was raw bytes then you'd have to increment the pointer by 
> 4 to move to the next element.
>
> This is counter-intuitive if you're moving to the next element 
> in a loop ex.
>
> This is how you'd do it idiomatically:
>
> ```d
> foreach (i; 0 .. list.length)
> {
>     (*cast(int*)(ptr + i)) = i;
> }
> ```

Is this `(*cast(int*)(ptr + i)) = i;` or you did a mistake and 
wanted to write: `(*cast(int*)ptr + i) = i;`? Cause like we said 
before, the first operand must be a cast to the type for this to 
work right.

> Compared to:
>
> ```d
>
> foreach (i; 0 .. list.length)
> {
>     (*cast(int*)(ptr + (i * 4))) = i;
> }
> ```

Got it! I guess they could also just allow us to use bracket 
notation to do the same thing. So something like:

```d
foreach (i; 0 .. list.length) {
   (cast(int*)ptr[i]) = i;
}
```

This is what happens with arrays anyways. And arrays ARE pointers 
to a contiguous memory block anyways so they could do the same 
with regular pointers. The example also looks more readable.


More information about the Digitalmars-d-learn mailing list