1. understanding pointer arithmetic

In my C programing class I was given an assignment to create an array stack only using pointers to keep track of and change the values, however the use of pointer arithmetic was not covered completely. The course book doesn't explain it either. I'm trying to understand how to do this.

The code I'm trying to learn with is:
Code:
```//test file
#include <stdio.h>

int stack[] = {11,22,33,44};
int *top = stack;

int main()
{
printf("%d\n",*top);//should print 11
*top = *(top + 1);

printf("%d\n",*top);//should print 22
*top = *(top + 1);

printf("%d\n",*top);//should print 33
*top = *(top - 1);

printf("%d\n",*top);//should print 22

scanf("%c");//keeps window open
return 0;
}```
and the output I get is:
Code:
```11
22
22
0```
Im having a little bit of trouble understanding this...

2. Welcome to the boards. Notice that there is a separate forum for C related questions, so you should probably post future questions there. I'm sure a moderator will move this one for you soon.

In the code you are not incrementing the pointer. (top + 1) adds 1 to the pointer, but doesn't change it. So throughout your code, top points to the first spot in the array and top + 1 points at the second. When you do (top - 1) you are actually getting undefined behavior because it tries to point to memory before the array.

The solution is probably to increment top with ++ rather than adding 1 to it. Using ++ will actually change what top points to.

3. weird, the first time I tried that it didnt work, but it works now

and the code works the same no matter if its in a c compiler or c++

4. Originally Posted by firstofthegreat
and the code works the same no matter if its in a c compiler or c++
Indeed. Your code has the same meaning in C and C++ (with only a minor quibble as <stdio.h> is deprecated -- slated for future removal -- in C++). The line "*top = *(top - 1);" yields undefined behaviour in both languages, as top points to the first element of the array named stack (i.e. anything is possible in either language). The rest of your code is equivalent in both languages.

In C++ there are preferred alternatives (eg iterators) so use of raw pointers is usually discouraged. That is why those in a C++ forum will often suggest questions like yours be asked in a C forum -- even though your problem is technically the same in both C and C++. Sort of a religious snobbery.