Pointer++ in c, weird part for me, why? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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 Respostas
+ 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