Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the different between *p++,* ++p,++*p in C language pointer? [duplicate]

Tags:

c

pointers

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?

like image 502
Bing Sun Avatar asked Nov 16 '25 02:11

Bing Sun


1 Answers

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.

like image 183
VHS Avatar answered Nov 17 '25 18:11

VHS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!