Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C (http://www.programmingforums.org/forum60.html)
-   -   How do I swap pointers with a function? (http://www.programmingforums.org/showthread.php?t=12506)

Thiengineer Feb 4th, 2007 6:41 PM

How do I swap pointers with a function?
 
I need help with the following problem about swapping pointers.

The following code is in main:
:

        main()
        {
          int x=1,y=2;
          int *xp,*yp;
          .
          .
          .
          xp = &x;
          yp = &y;
          intpswap(<arg1>,<arg2>);
          x=3;y=4;
          printf("*xp = %d, *yp = %d\n",*xp,*yp);
        }

Write a function called intpswap that swaps what xp and yp point at,
and thus printf prints "*xp = 4, *yp =3".

I know how to swap int values by using a temp variable, but is it the same approach here?

Any help or hints will be greatly appreciated!!

Thank you!!

DaWei Feb 4th, 2007 7:13 PM

Put one in a temp, put the second where the first was, and put the temp in the second.

Thiengineer Feb 4th, 2007 9:19 PM

This is what I have so far...am I on the right track? Please help!! You help is greatly appreciated!

void intpswap(int *xp, int *yp)
{
int t = *xp;
*xp = *yp;
*yp = t;
}

DaWei Feb 4th, 2007 11:23 PM

Why would you declare t as an int? You're swapping int pointers. Since you want persistent effects (I imagine), you need to pass pointers to the pointers to swap, since copies will simply go out of scope when the function returns.

Note that a and b are not swapped, despite what the printf SAYS, only the pointers are swapped.
:

#include <stdio.h>

void pSwap (int **a, int **b)
{
        int *temp = *a;
        *a = *b;
        *b = temp;
}

int main ()
{
        int a = 4;
        int b = 6;
        int *pA = &a;
        int *pB = &b;

        printf ("a: %d , b: %d\n", *pA, *pB);

        pSwap (&pA, &pB);
        printf ("(swapped) a: %d , b: %d\n", *pA, *pB);
}

Quote:

Originally Posted by Output
a: 4 , b: 6
(swapped) a: 6 , b: 4


jim mcnamara Feb 6th, 2007 4:02 PM

:

void swap( int *a, int *b)
{
        int t=*a;
        *a=*b;
        *b=t;
}

int main()
{
        int x=1;
        int y=2;
        int *a=&x;
        int *b=&y;
        printf("%d %d\n", *a, *b);
        swap(a,b);
        printf("%d %d\n", *a, *b);
        return 0;

}
kcsdev:/home/jmcnama> cc t.c
kcsdev:/home/jmcnama> ./a.out
1 2
2 1


FWIW. I think he meant to swap what the pointers were "aimed" at. Not the actual pointers themselves. But it doesn't matter....


All times are GMT -5. The time now is 2:01 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC