I am trying to decrement a pointer while setting values to what the pointer is poiting to. When setting the values they show that they have been properly set, but when trying to retrieve them again it doesnt return the right values. Why is this, and how can I get it to work?
This is the code I tried:
int a = 0;
int* sp = &a;
int* start_sp = &a;
for (int i = 0; i <= n; i++) {
*sp = i;
printf("%d, %d\n", *sp, sp);
sp--;
}
sp = start_sp;
printf("\n");
for (int i = 0; i <= n; i++) {
printf("%d, %d\n", *sp, sp);
sp--;
}
The output I get is:
0, 6291028
1, 6291024
2, 6291020
3, 6291016
4, 6291012
0, 6291028
1, 6291024
0, 6291020
6283584, 6291016
0, 6291012
Why is this happening?
As you access the memory which does not belong to any object, you invoke an undefined behavior.
To work you need to assign the pointer with the reference of the object (in this case an element of array) and you need to be sure that
sp - nreferences the same array;