Pointers question

Hello pals,

At todays class, we were doing some tasks with pointers. So here's the thing.

Program:

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main()
{
    int a[] = {1,0}, *p;
    p = a;
    printf("%d,",*p++);
    printf("%d\n",*p);
    return 0;
}


In my point of view, it should write down: 0,0 but it doesnt(1,0 is the result). Teacher had the same problem as im having now and he couldnt say why is it doing that way. My opinion, it should go from right to left(first ++ operator, then gets value of *p in printf). So, if someone knows how to explane it to me it would be great.

Thanks
++ has a higher precedence than *, so *p++ is the same as *(p++)

The trick here is what the postfix ++ operator actually does.

postfix ++ will increment the pointer, but will return the old value. For example:

1
2
3
int foo = 5;
cout << foo++;  // prints 5
cout << foo;  // prints 6 


This is different from the prefix ++ operator, which will return the new value:

1
2
3
int foo = 5;
cout << ++foo;  // prints 6
cout << foo;  // prints 6 



Your problem here is the same:

1
2
printf("%d,",*p++);  // prints *p (1).. THEN increments p to point to next element
printf("%d,",*p );  // prints *p (0) 
So it's doing it right?

Let me see if i got your point right.

++ operator, in that case doesn't have higher precedence so it first return value of *p and then increment it? Or what?
Last edited on
Plavsa wrote:
So it's doing it right?

Machine will always do what you tell it to do no questions asked.

Plavsa wrote:
++ operator, in that case doesn't have higher precedence so it first return value of *p and then increment it? Or what?


Answer bolded
Last edited on
Thanks for your answers. :)
Slightly worrying that your teacher didn't know what was going on.
Topic archived. No new replies allowed.