Results 1 to 7 of 7
print(int *a,int *b,int *c,int *d,int *e)
{
printf("%d %d %d %d %d",*a,*b,*c,*d,*e);
}
int main()
{
static int a[]={97,98,99,100,101,102,103,104};
int *ptr=a+1;
print(++ptr,ptr--,ptr,ptr++,++ptr);
printf("\n");
return 0;
}
output after running on ...
- 09-17-2007 #1Just Joined!
- Join Date
- Sep 2007
- Posts
- 11
problem with pointer increment operation
print(int *a,int *b,int *c,int *d,int *e)
{
printf("%d %d %d %d %d",*a,*b,*c,*d,*e);
}
int main()
{
static int a[]={97,98,99,100,101,102,103,104};
int *ptr=a+1;
print(++ptr,ptr--,ptr,ptr++,++ptr);
printf("\n");
return 0;
}
output after running on linux m/c is:
100 100 100 99 100
initially "ptr" stores the address of first element i.e. address ofa[1]. When "++ptr" is done, it should point to a[2]. But why is it pointing to a[3]?
- 09-17-2007 #2
Order of operations on pointers is pre-increment, pointer itself, post-increment. All of these go from left to right.
So:
First evaluates the pre increments and it's at sub 3, then it prints the middle ptr because it's not pre or post. At this point it is at sub 3, which is why ptr prints 100. When we get to ptr-- it first prints 100, then deincrements *ptr to sub 2. When we get to ptr++ it prints sub 2 which is 99, then after that evaluation, ptr is back at sub 3. Make sense?Code:print(++ptr,ptr--,ptr,ptr++,++ptr);
- 09-17-2007 #3
- 09-18-2007 #4
still confused...
i slightly modified the program...
#include <stdio.h>
print(int *a,int *b,int *c,int *d,int *e)
{
printf("%u %u %u %u %u\n", a, b, c, d, e);
printf("%d %d %d %d %d",*a,*b,*c,*d,*e);
}
int main(void)
{
static int a[]={97,98,99,100,101,102,103,104};
int *ptr=a+1;
int *aptr = a+1;
printf("%u\n", ptr);
printf("%u\n", ptr+1);
printf("%u %u %u %u %u\n", a, a+1, a+2, a+3, a+4);
printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]);
//printf("%u %u %u %u %u\n", ++aptr, aptr--, aptr, aptr++, ++aptr);
print(++ptr,ptr--,ptr,ptr++,++ptr);
printf("\n");
return 0;
}
output:--
134518596
134518600
134518592 134518596 134518600 134518604 134518608
97 98 99 100 101
134518604 134518604 134518604 134518600 134518604
100 100 100 99 100
.... i'm still confused.... from o/p it's clearly seen that initially ptr is pointing to a[1],
now when i print the value for ptr+1 it's correctly showing the address of a[2]... but instead after ++ptr why it is pointing to a[3] ???.... why it is skipping address of a[2]
[assuming (ptr=ptr+1) and (++ptr) are equivalent statements]......
- 09-18-2007 #5
i'm not sure.... does this problem have something to do with sequence point???.... i'm not sure... i read somewhere that when u pass the expression as function argument ... in which sequence the it'll evaluate it....
betn i also tried passing diffent pointer... like
int *x=++ptr;
int *y=ptr--;
int *z=ptr;
int *p=ptr++;
int *q=++ptr;
u'll get the desired o/p..........
- 09-19-2007 #6Just Joined!
- Join Date
- Sep 2007
- Posts
- 11
fine.thnq so much
- 09-19-2007 #7


Reply With Quote