Problems with pointer arithmetic

Hi guys! I've recently began studying pointers, but I've hit a big roadblock. To my understanding, once "p++" is executed, p should point to the next memory location in the array. Following that, "*p = 35" should assign 35 to the current address that p points to (i.e. p[1]). As you can see, that's not the case. The value of p[0] is 35, while the value of p[1] is 0. If I add "p--" after "*p = 35", the program works as expected. The only clues I've found elsewhere point (hehe) to something fishy going on with the precedence of operators and postfix/prefix notation. Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
int *p = nullptr;
p = new int[10];

*p = 25; 
p++;
*p = 35;
//if I add p-- here, it works

cout << p[0] << ' ' << p[1] << endl; 
//expected output: 25 35

delete [] p;
p = nullptr; //dealing with dangling pointers 
Last edited on
right... you be changing p.

typically you have a data pointer, where the data *IS* and this is not changed, and an iterator pointer, that hops around inside the thing.

eg
p = new int[10];
int* ip = p;

*ip = 25;
ip++;
*ip = 35;
cout << p[0] << ' ' << p[1] << endl;

that will work, because p has not changed! When you did p++, what that says is p = &p[1];
and now p[0] is what used to be p[1] and, worse, if you lose track you lose your data entirely (modification of the storage location can lose the start location and your data entirely) you will have a bug, a crash, or a memory leak lurking in the code.

and now the lectures :)
- don't mix and match * and [], its hard to read. I personally recommend using only [] notation as * gets confusing in math code, eg *p * *p to square p is downright ugly. It is also easier to change from a pointer to other things with [] notation (vector, array, etc can be changed without a lot of extra code, but * notation would require a re-write of much of the code).
your code can be summed up with a cleaner (to me) looking
p[0] = 25;
p[1] = 35;
cout << p[0] << ' ' << p[1] << endl;

- this kind of hands-on pointer stuff is best avoided as much as is possible in your code. C++ can avoid almost all low level pointer manipulations.

- it is a really, really good rule of thumb to not change (via assignment or arithmetic or anything else) any pointer that has been allocated with a new statement (exception, if it has also been deallocated with a delete statement you can then modify it). This avoids creating memory leaks, bugs, and problems in general -- there may be exceptions (like a circular linked list) that don't get 'lost'.
Last edited on
Thanks for the help! This is the first time I've heard of the "data and iterator pointer" approach and it really cleared things up for me. Thanks again!
honestly, I wouldn't use it, which may be why you have not heard of it.
I much, much prefer to loop over an index using [] than a second pointer that is being incremented.
Topic archived. No new replies allowed.