+ 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
5 ответов
+ 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?
+ 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.
+ 1
int x = 4;
int *p = &x;
int *k = p++; // p is post incremented
printf("%p %p", &x, k); // <= same address
+ 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 🙂
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…🥲