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

bauss jacobbauss at gmail.com
Mon Dec 5 08:21:44 UTC 2022


On Monday, 5 December 2022 at 06:12:44 UTC, rempas wrote:
> On Sunday, 4 December 2022 at 16:40:17 UTC, ag0aep6g wrote:
>>
>> Not quite. Adding 10 to a T* means adding 10 * T.sizeof.
>
> Oh! I thought it was addition. Is there a specific reasoning 
> for that if you are aware of?

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;
}
```

Compared to:

```d

foreach (i; 0 .. list.length)
{
     (*cast(int*)(ptr + (i * 4))) = i;
}
```


More information about the Digitalmars-d-learn mailing list