Can't modify array with pointer

Why line 8 (marked with comment) doesn't change array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main() {
    int tab[5] = { 1, 2, 4, 8, 16 };
    int *p1 = tab, *p2 = tab + 4;
    for(int *p = p1 + 1; p < p2; p++)
        *p = p[-1] * 2;                                   // line # 8 HERE!
    //cout << tab[1] << tab[2];

    cout << "========================================" << endl;
    for(int *p = p1; p <= p2; p++)
        cout << *p << endl;

    *(p1 + 2) = 666;
    p1[1] = 100;

    cout << "========================================" << endl;
    for(int *p = p1; p <= p2; p++)
        cout << *p << endl;

    return 0;
}


Output:

========================================
1
2
4
8
16
========================================
1
100
666
8
16

Author use "p" pointer as alias to range between p1 and p2.
I think it should works fine.
its writing the same values the array started with....
*p = p[-1]*2 generates the same numbers you initialised it with :) (item = double the item before it)
Last edited on
Holy cow, I'm sory, my mistake - don't catch this assignment.
Thanks a lot!
Topic archived. No new replies allowed.