- #1
- 2,076
- 140
Homework Statement
Not homework, but I don't really know where else to put this.
Below is some code and it's relevant output, but the output is what I'm concerned about.
Homework Equations
The Attempt at a Solution
Code:
#include <stdio.h>
#include <stdlib.h>
void foo(int a, int b) {
int r = a+b;
a += 2;
printf("(AR1) r = %d, a = %d \n", r, a);
}
void foo2(int *a, int *b){
*a = (*a)*2;
b = a;
printf("(AR2) *a = %d, *b = %d \n", *a, *b);
}
int main() {
int x = 5, y = 2;
int *p = &x, *r = &y;
printf("(AR3) x = %d, y = %d, *p = %d, *r = %d \n", x, y, *p, *r);
foo(x,y);
printf("(AR4) x = %d, y = %d, *p = %d, *r = %d \n", x, y, *p, *r);
foo2(p,r);
printf("(AR5) x = %d, y = %d, *p = %d, *r = %d \n", x, y, *p, *r);
r++;
printf("(AR6) x = %d, y = %d, *p = %d, *r = %d \n", x, y, *p, *r);
return 0;
}
This produces the following output:
Code:
(AR3) x = 5, y = 2, *p = 5, *r = 2
(AR1) r = 7, a = 7
(AR4) x = 5, y = 2, *p = 5, *r = 2
(AR2) *a = 10, *b = 10
(AR5) x = 10, y = 2, *p = 10, *r = 2
(AR6) x = 10, y = 2, *p = 10, *r = 10
Activation record 6 is of some interest. For some reason, when ##r++## is read, the pointer ##r## decides to point to the same value ##p## is pointing to (which is ##x = 10##).
Why does this happen?
Executing ##r++## again interestingly made ##r## point to zero.