Then q is decremented and assigned to temp
temp is assigned to the address that q is pointing to, and then q is decremented.
Remember that with "post" increment or decrement, the increment/decrement expression has the old value even though the variable will ultimately be incremented.
So this:
Code:
while (p < q){
temp = *p;
*p++ = *q;
*q-- = temp;
}
Is the same as this:
Code:
while (p < q){
temp = *p;
*p = *q;
++p;
*q = temp;
--q;
}
In your second version, since you don't use a temp variable to hold the initial value of p, after q is assigned to p, p equals q and therefore assigning it back to q just assigns q's original value back to q.
Code:
#include <stdio.h>
#define N 10
int main() {
int a[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *p = &a[0], *q = &a[N - 1], temp;
while (p < q){
temp = *p;
*p++ = *q;
*q-- = temp;
}
for (int i = 0; i < N; ++i)
printf("%d ", a[i]);
putchar('\n');
int a2[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *p2 = &a2[0], *q2 = &a2[N - 1];
while (p2 < q2) {
*p2 = *q2;
*q2 = *p2;
p2++;
q2--;
}
for (int i = 0; i < N; ++i)
printf("%d ", a2[i]);
putchar('\n');
return 0;
}
/*
Output:
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 6 7 8 9 10
*/