www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to get the pointer of an element from a slice using foreach?

reply ryuukk_ <ryuukk.dev gmail.com> writes:
Let's pretend i have this code:

```D

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:

```D
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?
Aug 10 2023
parent reply "Richard (Rikki) Andrew Cattermole" <richard cattermole.co.nz> writes:
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; } ```
Aug 10 2023
parent ryuukk_ <ryuukk.dev gmail.com> writes:
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!!
Aug 11 2023