Is D's pointer subtraction more permissive than C (and C++)?
Salih Dincer
salihdb at hotmail.com
Sat Apr 2 03:51:28 UTC 2022
On Friday, 1 April 2022 at 15:52:39 UTC, Ali Çehreli wrote:
> As the following quote from a Microsoft document claims, and as
> I've already known, pointer subtraction is legal only if the
> pointers are into the same array: "ANSI 3.3.6, 4.1.1 The type
> of integer required to hold the difference between two pointers
> to elements of the same array, ptrdiff_t." (
> https://docs.microsoft.com/en-us/cpp/c-language/pointer-subtraction?view=msvc-170 )
>
> I suspect "array" means "a block of memory" there because
> arrays are ordinarily malloc'ed pieces of memory in C.
> [...]
```d
import std.stdio;
enum testLimit = 1024 * 1024 * 62;
void main()
{
char[] first ="a12345".dup; // length =>6
first.length = testLimit;
first[$-1] = 'z';
auto hLen = first.length/2; // =>3
auto sliceRight = first[hLen..$];// "345"
char* oneHalf = &first[hLen++]; // =>[3]
char[] half12 = first[0..hLen]; // =>[0..4]
char[] half22 = oneHalf[0..hLen];// =>[0..4]
// legal? Ok.
--hLen; // =>3
for(int i; i < hLen; i++)
assert(&sliceRight[i] - &half12[i] == hLen);
// legal? Ok.
half12[0..3].write("..."); // "a12..."
sliceRight[$-3..$].writeln; // "��z"
char* a = &half12[0]; // "a"
char* z = &sliceRight[$-1]; // "z"
writefln("[%c]%s\n[%c]%s", *a, &(*a), *z, &(*z));
assert( (&(*z) - &(*a)) ==
(testLimit - 1) );
// legal? Ok.
auto test = half22.ptr - half12.ptr;
assert(test == hLen);/*
test.writeln;//*/
// legal? Ok.
auto last = first;
assert(first.ptr - last.ptr ==
0);
// legal? Ok.
last ~= '.';
assert(&last[$-1] - &first[$-1] == 1);
}
```
Everything is legal...
SDB at 79
More information about the Digitalmars-d
mailing list