Please refer to the below code
Please explain me the line : short* end = a + SIZE;
end is a pointer variable which holds address. a is the address of a[0]. But SIZE is a constant of value 3. How is it being added to a ? Size of short is 2 bytes. Here 6 is getting added to a despite its value being 3. Please explain
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{ constint SIZE = 3;
short a[SIZE] = {22,33, 44};
cout << "a = " << a << endl;
cout << "sizeof(short) = " << sizeof(short) << endl;
short* end = a + SIZE; // converts SIZE to offset 6
short sum = 0;
for (short* p = a; p < end; p++)
{ sum += *p;
cout << "\t p = " << p;
cout << "\t *p = " << *p;
cout << "\t sum = " << sum << endl;
}
cout << "end = " << end << endl;
}
I understand basic pointer arithmetic and have gone through the links given by you. If it would have been short* end = &a[SIZE], I agree and understand it. But please explain what is happening in short* end = a + SIZE ?
The compiler knows what size all the types are, so if short is 2, and you add 3 to the pointer, it knows that it has to add 3 *2 to the pointer to obtain the end address.
Put another way, when you add the number 3 to the pointer, you're not asking to increment the pointer by 3 bytes of memory. You're asking to increment it by however much memory is equal to the size of 3 times the thing it's pointing at.