Recovering the index of an array element

In the course of reworking some “C” code, I came across the need to obtain the index of an array element knowing the array and a pointer to the element. The old “C” hack in me just subtracts the address of the first element in the array from the element pointer. The Zig compiler let me know in no uncertain terms that such an operation is not allowed. In looking at the language reference it is clear that pointer arithmetic is only allowed in limited circumstances.

So my question is, “Is there a canonical means in Zig to recover the index of an array element given the array and a pointer to one of its elements?”

Try using @intFromPtr: Documentation - The Zig Programming Language

Then you can do all the arithmetic you need :slight_smile:

1 Like

@AndrewCodeDev’s workaround is the short-term solution.

Long term solution is this accepted proposal: support pointer subtraction · Issue #1738 · ziglang/zig · GitHub

3 Likes

Thanks. I figured I could whip it into submission with a big enough casting hammer and taking over the necessary scaling of the difference. Just wanted to make sure I hadn’t missed something or that the thought of using the old tricks of a “C” hack coder would not cause a case of apoplexy in the core team. :slight_smile:

1 Like

Great work, Andrews! I think we have this thread about wrapped up. :handshake:

3 Likes