I'm trying to understand pointers in a little more detail, and have
written a test program (reproduced below) to experiment with passing
pointers between functions.
Thinking only about the variable x in main, I would expect the
following to happen:
- &x is passed to func_one, so int* p1x is pointing to x (int* p1x =
&x)
- func_one then dereferences p1x to increment x; at this point x = 1
- func_one passes p1x to func_two, so int* p2x = p1x and pointers p2x
and p1x both point to x
- func_two then dereferences p2x to increment x; at this point x = 2
- control passes back to main() and the value of x is printed
Therefore, I would expect this program to produce the output "x = 2; y
= 2; c = 1", but it doesn't. Can anyone provide any insight into why
this is the case?
Thanks in advance
Simon
--code follows --
#include <stdio.h>
void func_two (int* p2x, int* p2y)
{
*px ++;
*py ++;
}
void func_one (int* p1x, int* p1y, int* p1c)
{
*pc ++;
*px ++;
*py ++;
func_two (px, py);
}
int main (void)
{
int x, y, c, d;
x = y = c = 0;
func_one (&x, &y, &c);
printf("x = %d; y = %d; c = %d", x, y, c);
d = getchar();
return 0;
}