When you modify p
in the loop (p++
) you loose the original pointer, so after the loop p
will point somewhere else. All dereferencing of p
after that loop will cause undefined behavior.
If you want that outcommented loop to work, without changing p
, you have to do it using a temporary variable:
int** t = p;
for (int i=0; i<2; i++, t++)
*t = new int(y--);
Note: If you run both allocation loops, you will have a memory leak as the pointers allocated by the first loop will be overwritten.