Reputation: 337
#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?
Upvotes: 3
Views: 221
Reputation: 30146
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.
Upvotes: 2
Reputation: 206717
You asked:
Why does
*ptr++
which is aptr1
point toptr3
's Address?
First of all,
*ptr++;
is the same as
*(ptr++)
The side effect the expression is that ptr
is incremented, the pointer is dereferenced, and the dereferenced value is discarded. Dereferencing ptr
after it is incremented is itself cause for undefined behavior. Anything you get after that is potentially unreliable.
As to why ptr
points to ptr3
's address, I am not sure why you think that. Your output doesn't seem to indicate that.
You also asked,
and why does
*++ptr4
have a value 1000 which isptr3
's value?
The expression *++ptr4
suffers from the same problem. You are incrementing ptr4
, and dereferencing the incremented pointer. What you get from dereferencing that pointer is cause for undefined behavior, and hence, unpredictable.
Depending on how your stack is organized, it's quite possible that ptr4
points to the same address as ptr3
after it is incremented. However, don't count on such coincident behavior.
Upvotes: 1
Reputation: 87391
The relative memory order of the int
s in your code is undefined. Use an array to put them next to each other, in increasing order:
int op[] = {9, 99, 999, 9999};
int *ptr1 = &op[0], *ptr2 = &op[1], *ptr3 = &op[2], *ptr4 = &op[3];
To print pointers, use the %p
format specifier.
Upvotes: 0