0

Hi can someone explain to me why i get the results

1: 4 3
2: 3 4
3: 3 4
4: 3 4
5: 3 3
6: 3 4

for the following code?

 #include<stdio.h>



void switch2(int *a, int *b)
{
    int hold;
    hold = *a;
    *a = *b;
    *b = hold;
    return;
}

void switch3(int *a, int *b)
{
    int *hold;
    hold = a;
    a = b;
    b = hold;
    return;
}

int main()
{
    int x=3, y=4, *p=&x, *q=&y, *hold;
    switch2(&x, &y);
    printf("1: %d %d\n",x,y);
    switch2(p,q);
    printf("2: %d %d\n", *p, *q);
    switch3(&x,&y);
    printf("2: %d %d\n",x,y);
    switch3(p,q);
    printf("4: %d %d\n", *p, *q);

    hold = p;
    p = q;
    q = hold;
    printf("5: %d %d\n", *p, *q);
    printf("6: %d %d\n", x,y);
    return 0;
}

(Sorry im unable to code wrap.the buttons seem to be stuck when i clikc on them)

Edited by Dani: Formatting fixed

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by Ancient Dragon
0

switch() is just swapping the variable addresses (which are local to switch funcction), instead of the values stored at those addresses

void switch(int* x, int* y)
{
   int hold = *x;
   *x = *y;
   *y = hold;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.