c - Swap using Pointers -
in code below in order swap between px
, py
need pointer point address of py
, px
swap them effectively.
my question int temp
when value of px
put how give correct value because there no pointer pointing able give right value , how address of int temp
not clone give wrong value?
void swap(int px, int py) { int temp; temp = px; px = py; py = temp; } //pointer version void swap(int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; }
both functions swap int
values. swap affect calling code's int
s?
with second swap()
, effect of swap seen in original a,b
function works addresses of original a,b
.
int = 1; int b = 2; swap_version2(&a, &b); printf("%d %d\n", a, b); // prints 2 1
with first swap()
, effect of swapped not seen in original c,d
. swap()
function swapping copies of c,d
. net effect: first swap function wastes time. not swap c,d
.
int c = 3; int d = 4; swap_version1(c, d); printf("%d %d\n", c, d); // prints 3 4
Comments
Post a Comment