Ok, so on a test I had this question asked:
int* ptrA; // assigned memory address 100
int a = 1; // assigned memory address 600
ptrA = &a;
What is the memory address of ptrA + 2?
I thought it was 606 (int is 4 bytes + the address of a which is 600 + 2 = 606 but apparently the answer was 608, what am I missing to make this true?
It’s undefined behavior, the expression
PtrA + 2is illegal. You can only do pointer arithmetic on pointers you own and can’t add or substract to/from pointers outside the range of an array you own or one beyond the range.We can still analyze this however (although useless, because of UB). You assume the address of
ais600 + 2, but it’s not, since probablysizeof(int*)is also4, so this becomes600 + 4. So you get600 + 4 + 4 = 608.