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 is 0x FF FF FF FF. Because it's an unsigned integer, the -1 is overflowing and actually represents 4 294 967 295.
Your pointer is to an integer (int*), so each increment actually increments the address by sizeof int, which is 4 on a standard x86 machine. So we're actually adding 0x 03 FF FF FF FC (which is 0x FF FF FF FF * 4).
Now let's add the two together.
0x 00 12 34 56 78
+ 0x 03 FF FF FF FC
-------------------
0x 04 12 34 56 74
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 04 at the start. This results in 0x 12 34 56 74, which is 0x 12 34 56 78 - 4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With