-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Pointers to array types should have sane pointer arithmetic #7159
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
What benefit would this add other than making slightly more sense to programmers coming from C? This also makes the language more inconsistent since it adds another special case. I am not a big fan of this idea. If you need to offset the pointer, just index the array and take the address of the result. Or, possibly, take a pointer to the first element and do arithmetic on that. |
Duplicate of #2018. I'll add a "bug", "breaking", and "miscompilation" label to the issue since the status quo before is incorrect. |
I agree with @theInkSquid: |
I'm not trying to propose anything -- this is simply a bug report -- so could you clarify what it is you think I'm proposing that you don't like? Specifically, the issue is that according to the docs, pointer arithmetic only works on multi-item var x: i32 = 5;
var array: [8]i32 = [8]i32{ 1, 2, 3, 4, 5, 6, 7, 8 };
// These don't compile:
// Correctly disallowed
const p1 = &x + 1;
// Correctly disallowed (can't "take a pointer to the first element and do arithmetic on that")
const p2 = &array[0] + 1;
// These *do* compile:
// Correctly allowed -- p3 points to array[1]
const ptr_to_items: [*]i32 = &array;
const p3 = ptr_to_items + 1;
// Incorrectly allowed -- p4 points to the empty space after the end of array
const p4 = &array + 1; With
I'm not sure what generic code you have, but if any generic code depends on this behavior, it would already be failing to compile for non-array types. |
Pointers to array types (such as
*[8]u8
) allow arithmetic, but add multiples of the whole array, not of the element.In this example, adding
1
to&arr
results in a dangling pointer to the 8-byte chunk followingarr
in memory. I would expect&arr + offset
to either be an error, or result in a pointer to theoffset
'th element of the array.The text was updated successfully, but these errors were encountered: