The following results do not make any sense to me. It appears that the negative offset is cast unsigned before addition or subtraction is performed.
double[] x = new double[1000]; int i = 1; // for the overflow it makes no difference if it is long, int or short int j = -1; unsafe { fixed (double* px = x) { double* opx = px+500; // = 0x33E64B8 //unchecked //{ double* opx1 = opx+i; // = 0x33E64C0 double* opx2 = opx-i; // = 0x33E64B0 double* opx3 = opx+j; // = 0x33E64B0 if unchecked; throws overflow exception if checked double* opx4 = opx-j; // = 0x33E64C0 if unchecked; throws overflow exception if checked //} } }
Although it may seem strange to use negative biases, there are use cases for it. In my case, this reflected the boundary conditions in a two-dimensional array.
Of course, the overflow doesnβt hurt too much, because I can either use unchecked or move the sign of the value to the operation, inverting and applying it to the operand module.
But this behavior seems undocumented. According to MSDN, I do not expect negative biases to be problematic:
You can add a n value of type int, uint, long or ulong to the pointer p of any type except void *. The result p + n is the pointer that results from adding n * sizeof (p) to p. Similarly, pn is a pointer resulting from subtracting n * sizeof (p) from address p.
source share