pointers - Why can't I swap memory address of two variables using a function? C -
static void swapaddr(int *numone, int *numtwo) { int *tmp; tmp = numone; numone = numtwo; numtwo = tmp; } int main(void) { int = 15; int b = 10; printf("a is: %d\n", a); printf("address of a: %p\n", &a); printf("b is: %d\n", b); printf("address of b: %p\n", &b); swapaddr(&a, &b); printf("\n"); printf("a is: %d\n", a); printf("address of a: %p\n", &a); printf("b is: %d\n", b); printf("address of b: %p\n", &b); return 0; }
when compile , run piece of code, output
a is: 15 address of a: 0x7fff57f39b98 b is: 10 address of b: 0x7fff57f39b94 is: 15 address of a: 0x7fff57f39b98 b is: 10 address of b: 0x7fff57f39b94
clearly result not intended, since address not seem have been swapped @ all.
you can't change address of variable.
your 'swapaddr' function changes parameter values, these local function - you're not changing outside function. perhaps best way of understanding function parameter receives copy of value passed function. in case, copy of address of a
, copy of address of b
. can , change values of variables holding copies (numone
, numtwo
), , seeing pointers (but don't) change values point @ (the values of variables a
, b
) - can't change addresses of original variables.
to break down:
static void swapaddr(int *numone, int *numtwo) { int *tmp; tmp = numone;
at point, tmp
, numone
both point value of a
variable...
numone = numtwo;
now, numone
points instead value of b
variable...
numtwo = tmp; }
and finally, numtwo
points value of a
variable. function returns , numone
, numtwo
no longer exist after point. addresses of variables a
, b
did not change @ stage.
you could write function exchanges addresses in 2 pointer variables:
static void swapaddr(int **ptrone, int **ptrtwo) { int *tmp; tmp = *ptrone; *ptrone = *ptrtwo; *ptrtwo = tmp; }
this allow pass address of 2 pointer variables, , on return pointers swapped - each 1 pointing @ other did previously. again, not change address of variable pointers happened point to.
Comments
Post a Comment