Below is the problem I found on the internet.
int main()
{
int a[4] = { 10, 21, 32, 43};
int *p = a 3;
*--p;
*p--;
p[2] = p[1];
for (int i = 0; i < 4; i)
printf("%d - %d\t", a[i]);
return 0;
}
//What will be the output?
answer : 10 21 34 77
I understood a lot of things, but the only thing I'm stuck on:
What is the difference between ( *--p) and ( *p--) ?
Shouldn't these two give the same result? Because (*p--) and (*--p) give the same result in the compiler. The compiler I use is Code::Blocks
CodePudding user response:
Because
(*p--)and(*--p)give the same result in the compiler.
No, they do not. *p-- decrements p but applies * to the value of p before the decrement. *--p applies * to the value of p after the decrement.
What is the difference between
( *--p)and( *p--)?
*--p decrements p and increments the object it points to after the decrement.
*p-- decrements p but increments the object it points to before the decrement.
CodePudding user response:
What is the difference between
( *--p)and( *p--)?
The difference is that --p decrements p and resolves to the new value of p, whereas p-- decrements p and resolves to the old value of p.
* works identically on both - performing indirection on p, incrementing the value p points to, and resolving to this new value.
#include <stdio.h>
int main(void)
{
int a = 10;
int b = 10;
/* This prints 9, and `a` is now 9 */
printf("%d\n", --a);
/* This prints 10, and `b` is now 9 */
printf("%d\n", b--);
/* This prints 9 and 9 */
printf("%d %d\n", a, b);
}
Shouldn't these two give the same result? Because
(*p--)and(*--p)give the same result in the compiler.
The order here matters, using (*--p) before (*p--) would resolve to the same element twice. Using (*p--) before (*--p) resolves to different elements.
#include <stdio.h>
int main(void)
{
int a[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int *p = a 4;
/* 4 then 4 */
printf("%d ", *--p);
printf("%d\n", *p--);
p = a 4;
/* 5 then 3 */
printf("%d ", *p--);
printf("%d\n", *--p);
}
