Incase of pointer arithmetic, are the integers automatically converted to their signed variants? If yes, why?
Suppose I do
int *pointer;
int *pointerdiff;
unsigned int uiVal = -1;
pointerdiff = pointer + uiVal // Pointer will contain valid address here.
where pointer is a pointer to int and uiVal is initialized to -1, then I find that the address in pointers get decremented by 4. Why is the unsigned value of -1 not considered here?
It looks like your pointer is overflowing.
Let’s do some maths. Say you’re on a 32-bit machine, and your pointer is initialised to
0x 12 34 56 78. We then initialise an unsigned int variable to-1, which is0x FF FF FF FF. Because it’s an unsigned integer, the-1is overflowing and actually represents4 294 967 295.Your pointer is to an integer (
int*), so each increment actually increments the address bysizeof int, which is 4 on a standard x86 machine. So we’re actually adding0x 03 FF FF FF FC(which is0x FF FF FF FF * 4).Now let’s add the two together.
Of course, this overflows, because we now have a 40-bit value, and a pointer is 32 bits and can only hold that much information. We therefore lose the
04at the start. This results in0x 12 34 56 74, which is0x 12 34 56 78 - 4.