Evaluation work on indexing and incrementing
#include <stdio.h>
int main() {
int op9=9;
int op99=99;
int op999=999;
int op9999=9999;
int *ptr1=&op9,*ptr2=&op99,*ptr3=&op999,*ptr4=&op9999;
*ptr1++;
++*ptr2;
(*ptr3)++;
*++ptr4;
printf("%d=ptr1 \t %d=ptr2 \t %d=ptr3 \t %d=ptr4",ptr1,ptr2,ptr3,ptr4);
printf("\n %d = *ptr++ \n %d = ++*ptr \n %d = (*ptr)++ \n %d = *++ptr",*ptr1,*ptr2,*ptr3,*ptr4);
printf("\n \n %d=ptr1 \t %d=ptr2 \t %d=ptr3 \t %d=ptr4",ptr1,ptr2,ptr3,ptr4);
return 0;
}
This is the result I am getting
-
209002336=ptr1 -209002344=ptr2 -209002348=ptr3 -209002348=ptr4
-209002348 = *ptr++
100 = ++*ptr
1000 = (*ptr)++
1000 = *++ptr4
-209002336=ptr1 -209002344=ptr2 -209002348=ptr3 -209002348=ptr4
Why * ptr ++ which is the point of ptr1 for the address ptr3? and why is * ++ ptr4 value 1000 which is ptr3 value?
I thought * ptr1 ++ would point to the next address, and since it's not part of my program, I expected the program to crash. Likewise * ++ ptr4 should also do the same because it evaluates to * (++ ptr4).
So how does the Increment and Indirection Operator work for * ptr ++ and * ++ ptr?
source to share
Explanation 1000 = *++ptr4
:
Formally, this behavior is undefined.
In practice, local variables are allocated on the stack sequentially and in reverse order:
int op9; // SP+3
int op99; // SP+2
int op999; // SP+1
int op9999; // SP+0
So, taking a pointer to op9999
and incrementing it, it ends with op999
.
Keep in mind that this is still undefined behavior according to the C language standard.
This effectively means that you can get different results using different compilers.
source to share
You asked:
Why
*ptr++
, which isptr1
, points to anptr3
Address?
First of all,
*ptr++;
coincides with
*(ptr++)
A side effect of the expression is that it is ptr
incremented, the pointer is dereferenced, and the dereferenced value is discarded. The highlight ptr
after it has grown is itself the cause of undefined behavior. Anything you get after that is potentially unreliable.
As for why it ptr
points to an address ptr3
, I'm not sure why you think so. Your conclusion does not seem to indicate this.
You also asked:
and why
*++ptr4
does 1000 matterptr3
?
The expression *++ptr4
suffers from the same problem. You are incrementing ptr4
and dereferencing an incrementing pointer. What you get from dereferencing this pointer causes undefined behavior and therefore unpredictable.
Depending on how your stack is organized, it is quite possible that it ptr4
points to the same address as ptr3
after increasing it. However, do not expect this overlapping behavior.
source to share