3

I'm learning the basic knowledge of c programming language. And now I am confused at pointer sections. There is the original question in the book:

Array a has some value and pointer p is now at a[1]:

a[0]:10
a[1]:20  <---p
a[2]:30
a[3]:40
a[4]:50

Question List:

  1. What's the value of *p after executes * p++?
  2. What's the value of * ++p?
  3. What's the value of ++ * p?

So, What's the different between *p++, * ++p, ++*p?

In my opinion:

  1. *p++ means to move pointer p points the next element, so the 1st answer is 30.
  2. The difference of *p++ and *++p just like the difference of i++ and ++i. so the 2nd answer is 30.
  3. *p means the value of pointer p, so ++*p means to let p value increase 1. So the 3rd answer is 21;

Am i right?

Dai
  • 141,631
  • 28
  • 261
  • 374
Bing Sun
  • 205
  • 1
  • 3
  • 10
  • 3
    Your reasoning is correct, but the question is perhaps badly-worded: if the statement is `int q = *p++;`, `p`, as you say, is now pointing to `30`, but `q` equals `20`. `int q = *++p;` results in `p` pointing to `30`, and `q` also equals `30`. – Ken Y-N Feb 14 '17 at 02:33
  • You can have a good idea by trying it yourself with your preferred compiler. – Phil1970 Feb 14 '17 at 02:35
  • 1
    Are the questions supposed to be independent from the same start; or do you do 1, then 2, then 3? – M.M Feb 14 '17 at 02:53
  • @M.M: these 3 questions are from the same start -- possibly... the book have not describe. – Bing Sun Feb 14 '17 at 03:04

1 Answers1

6

What's the value of *p after executes * p++?

*p++ first dereferences the pointer p and then increments the pointer p. So the next call to *p will return 30.

What's the value of * ++p?

Consider the following example:

int array[] = {10, 20, 30};
int * p = array;

In this case, * ++p will print 20. First the pointer will be incremented meaning that it will start pointing to the second element. Then it will be dereferenced.

What's the value of ++ * p?

Consider the following example:

int array[] = {10, 20, 30};
int * p = array;

Here ++ *p will print 11. First the pointer will be dereferenced returning 10 which then will be incremented by 1 to return 11.

VHS
  • 9,534
  • 3
  • 19
  • 43