On Sun, Dec 24, 2006 at 12:50:10AM +0530, Arun G Nair wrote:
> Hi,
>
> Am a bit confused by the output of the this C program:
>
> -------------------------------------------------------------ptr.c---
> #include <stdio.h>
>
> int
> main()
> {
> int *ptr, x;
>
> x = 2;
> ptr = &x;
>
> printf("x=%d, *ptr=%d, ptr=%p, &x=%p\n", x, *ptr, ptr, &x);
>
> *ptr++;
> printf("x=%d, *ptr=%d, ptr=%p, &x=%p\n", x, *ptr, ptr, &x);
>
> ++(*ptr);
> printf("x=%d, *ptr=%d, ptr=%p, &x=%p\n", x, *ptr, ptr, &x);
>
> return 0;
> }
>
> --------------------------------------------------------------------------
>
> The output I get is this:
>
> $ ./a.out
> x=2, *ptr=2, ptr=0xbfbfece0, &x=0xbfbfece0
> x=2, *ptr=-1077941020, ptr=0xbfbfece4, &x=0xbfbfece0
> x=2, *ptr=750764012, ptr=0xbfbfece5, &x=0xbfbfece0
> ---------------------------------------------------------------------------
>
> If ++(*ptr) is supposed to increment the value *ptr, then why is there a
> change in memory address (0xbfbfece5) ?
Because *ptr++ is equivalent to *(ptr++)? Try:
#include <stdio.h>
int main(void) {
int *i, x[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
for (i = x; i < x + 9; )
printf("%d\n", *i++);
return 0;
}
And note that the equivalent with (*i)++ does something very different.
Joachim