How to swap pointers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thiengineer
    New Member
    • Feb 2007
    • 5

    How to swap pointers

    I don't know how to approach this problem, please help!

    The following code is in main:

    Code:
    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); 
            }
    Question:

    Write a function called intpswap that swaps what xp and yp point at,
    and thus printf prints "*xp = 4, *yp =3".
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    post what you have done so far

    Comment

    • Thiengineer
      New Member
      • Feb 2007
      • 5

      #3
      This is what I have so far...am I on the right track? Please help!!

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

      Comment

      • willakawill
        Top Contributor
        • Oct 2006
        • 1646

        #4
        Originally posted by Thiengineer
        This is what I have so far...am I on the right track? Please help!!

        void intpswap(int *xp, int *yp)
        {
        int t = *xp;
        *xp = *yp;
        *yp = t;
        }
        On the right track with some distance still to cover :)
        with
        Code:
        int t = *xp;
        You are assigning the value '1' to the int 't'
        with
        Code:
        *xp = *yp;
        you are assigning the value that yp points to, 2, to the memory space that xp points to, x. So x now equals 2
        with
        Code:
        *yp = t;
        you are assigning the value at t, 1, to where yp points to, y. So now y = 1
        The original pointers xp and yp have not changed. In order to change them we have to pass a reference to them:
        Code:
        void intpswap(int **xp, int **yp)
        {
           int *t = *xp;
           *xp = *yp;
           *yp = t;
        }
        
        int main() {
        	int x=1,y=2;
        	int *xp,*yp;
        
        	xp = &x;
        	yp = &y;
        	intpswap(&xp, &yp);
        
        	x=3;y=4;
        	printf("*xp = %d, *yp = %d\n",*xp,*yp); 
        
        	getchar();
        	return 0;
        }
        see if you can tell us what is happening here

        Comment

        Working...