#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 Output I get
-
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 does *ptr++ which is a ptr1 point to ptr3's Address? and why does *++ptr4 have a value 1000 which is ptr3's value?
I thought *ptr1++ will point to the next address and since its not part of my program I expected the program to crash. Similarly *++ptr4 should also do the same because its evaluated as *(++ptr4).
So how exactly does Increment and Indirection Operator work for *ptr++ and *++ptr?
Explaining the 1000 = *++ptr4:
Formally, this is undefined behavior.
Practically, the local variables are allocated in the stack consecutively and in reversed order:
int op9; // SP+3
int op99; // SP+2
int op999; // SP+1
int op9999; // SP+0
So by taking a pointer to op9999 and incrementing it, it ends up pointing to op999.
Keep in mind that it is still undefined behavior according to the C-language standard.
This effectively means that you may get different results when using different compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With