Pointer and arrays

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()
{ const int 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;
}
Last edited on
It's called pointer arithmetic.
https://www.eskimo.com/~scs/cclass/notes/sx10b.html
https://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm

Take a look, if you're still stuck, please ask again.
Last edited on
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 ?
Last edited on
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.
Thanks all. I understand now. It is like

end = &a[0]+3;Just like end = end +1 moves pointer to next memory location, similarly end = &a[0]+3 moves it by 3 memory locations
Last edited on
But please explain what is happening in
It is actually equivalent.

You can write an expression like this:

short* end = SIZE + a; which is equivalent to short* end = a + SIZE

hence you can write:

short* end = &SIZE[a] which is equivalent to short* end = &a[SIZE]
Topic archived. No new replies allowed.