Thread overview
How to get the pointer of an element from a slice using foreach?
Aug 10
ryuukk_
Aug 12
ryuukk_
August 10

Let's pretend i have this code:


Stuff[] mystuff;

foreach (item; mystuff)
{
}

How do i get a pointer?

I can get a reference if i prefix item with ref, but i need a pointer specifically, it can't be impossible, can it?

I could do:

foreach (i, item; mystuff)
{
    auto ptr = &mystuff[i]
}

But this is slow, now does bound checking twice..

I can also fall back to using a C loop, but i'd rather use D for loop

If not possible, why? and what does it take to add support for it in the compiler?

August 11
On 11/08/2023 10:35 AM, ryuukk_ wrote:
> I can get a reference if i prefix |item| with |ref|, but i need a pointer specifically, it can't be impossible, can it?

You're over thinking it. A variable that is a ``ref`` is a pointer with syntax niceties.

```d
void func(ref int val) {
	int* ptr = &val;
}
```
August 12
On Friday, 11 August 2023 at 04:38:11 UTC, Richard (Rikki) Andrew Cattermole wrote:
> On 11/08/2023 10:35 AM, ryuukk_ wrote:
>> I can get a reference if i prefix |item| with |ref|, but i need a pointer specifically, it can't be impossible, can it?
>
> You're over thinking it. A variable that is a ``ref`` is a pointer with syntax niceties.
>
> ```d
> void func(ref int val) {
> 	int* ptr = &val;
> }
> ```

Ohhh i didn't know this was possible, thanks!!