Pointer++ in c, weird part for me, why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Pointer++ in c, weird part for me, why?

I do code challenge and get confused, please tell me if you know why it act like this. Below is the question: What is the output of this code? int x = 4; int *p = &x; int *k = p++; int r = p - k; printf("%d", r); The answer is 1, and I don’k know why k’s value is 1 int size before p, suppose if they are int variable(that is int p = x, int k = p++), then the value of p and k are the same, But why does this not work the same rule in pointer++ and assignment, sorry for my bad English, and thank you

20th Jan 2022, 5:14 PM
張春德
張春德 - avatar
5 Answers
+ 4
<p> is post-incremented here int* k = p++; So <k> gets a copy of address stored in <p> before <p> was incremented. Is this what you asked for?
20th Jan 2022, 6:38 PM
Ipang
+ 1
P is and address to x, k is the same address locations plus 1, therefore 1 minus the original address is 1 which is r. I see what you are saying now it should be -1 not 1.
20th Jan 2022, 5:25 PM
William Owens
William Owens - avatar
+ 1
int x = 4; int *p = &x; int *k = p++; // p is post incremented printf("%p %p", &x, k); // <= same address
20th Jan 2022, 6:59 PM
rodwynnejones
rodwynnejones - avatar
+ 1
William Owens Ok, i see now, you are right, thanks 🙂 Ipang thanks bro, i know what’s going on now 🙂 rodwynnejones yup, you are right, thanks 🙂
20th Jan 2022, 9:53 PM
張春德
張春德 - avatar
0
No, in your opinion, p - k will be -1, run the code then print the address of them, then you will know that k is address of p minus 1, that’s why the weird part and i don’k know why…🥲
20th Jan 2022, 5:29 PM
張春德
張春德 - avatar