Mistake
Pointer p is already pointing to first element of array, after decrement operation (--p), p starts pointing to a location that is not allocated (outside the array) — causes undefined behaviors.
Basic Approach
First you need to understand that en array expression a[i] is equivalent to *(a + i) that is also equivalent to *(p + i) if p is pointer to first element of array. Further, a[i - 1] can also be written as *(a + i - 1) and that is equivalent to expression *(p + i - 1).
In declaration of p:
int* p = a;
array name decays to address of first element in array (that is same as of &a[0]).
Now, following is reverse loop - iterating backwards from last position in array.
for (int i = length - 1; i > 0; i--)
a[i - 1] += a[i];
it can also be written as:
for (int i = length - 1; i > 0; i--)
*(a + i - 1) += *(a + i);
and so can be written as
for (int i = length - 1; i > 0; i--)
*(p + i - 1) += *(p + i);
Correction in your Code
This is just a simple translation of your code in the form of p pointer to first element.
Lets we take a new approach and understands what does actually the loop do:
for (int i = length - 1; i > 0; i--)
a[i - 1] += a[i];
Operation a[i - 1] += a[i]; is same as a[i - 1] = a[i - 1] + a[i];. That means — in loop, in each iteration, value at i th position is added to i - 1 where value of i is 2 >= i > 1. See:
for (int i = 3 - 1; i > 0; i--)
// ^^ == 2
a[i - 1] = a[i - 1] + a[i];
so, if initial value of array is: a[3] = { 2, 1, 3 }; then each iteration is:
// 0 1 2
{ 2, 1, 3 };
i = 2
a[2 - 1] = a[2 - 1] + a[2];
a[1] = a[1] + a[2]
{ 2, 4, 3 };
i = 1
a[1 - 1] = a[1 - 1] + a[1];
a[0] = a[0] + a[1]
{ 6, 4, 3 };
In the above loop, you iterates back and adds current i index value to previous index. Note because in each iteration you access one element at i - 1 so loop has to be break at i == 1 or we can say at i > 0.
lets rewrite correct code in the way you wanted to be write:
const int length = 3;
int a[3] = { 2, 1, 3 };
int* p = a + length - 1; // now `p` points to `&a[2]`
for (int i = length - 1; i > 0; i--)
*(p - 1) += *p;
--p;
Better Approach
Now, still this is quite verbose code, we can improve it as follows:
int a[3] = { 2, 1, 3 };
for (int* p = &a[2]; p != a; --p)
*(p - 1) += *p;
Better Code
int a[] = { 2, 1, 3 };
int length = sizeof(a) / sizeof(*a);
for (int* p = a + length - 1 ; p != a; --p)
*(p - 1) += *p;
Give it a Try!!
+=in your codea[i - 1] += a[i];doens't looks same as of*(p - 1) = *p;