Thread: swapping values with pointers

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    29

    swapping values with pointers

    this program is supposed to take in two values, then use a function [void swap(( double *, double *);] to swap the variables and print them out. I was working on it with a friend of mine and he said something about needing another variable to do the swap and I just didn't understand what he was trying to say. Thanks for the help.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
        void swap (double *, double *);
        
        double *ptrA, *ptrB;
        double a, b;
     
        
        ptrA = &a;
        ptrB = &b;
        
        printf ("Please enter two numbers.");
        scanf ("&#37;d %d", &a, &b);
        
        printf ("\nNumber 1 is: %d",a);
        printf ("\nNumber 2 is: %d",b);
        
        
        swap (&a, &b);
        
        system("PAUSE");
        return 0;
    }
    
        void swap (double *ptrA, double *ptrB) {
    
             
             *ptrA = *ptrB;
             *ptrB = *ptrA;
             
    
             
             printf ("\n\nNew number 1 is %d:",*ptrA);
             printf ("\nNew number 2 is %d:\n\n",*ptrB);
    }

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You definitely need a temporary variable for the swap. Here's why.

    First of all, here's what your code is doing.
    Code:
    // *ptrA = 1, *ptrB = 2
    *ptrA = *ptrB;
    // *ptrA = 2, *ptrB = 2
    *ptrB = *ptrA;
    // *ptrA = 2, *ptrB = 2
    As you can see, the value of ptra is lost in the first step. You need to save the value of ptrA, and assign it to ptrB in the last step. Something like this.
    Code:
    // *ptrA = 1, *ptrB = 2, temp = undefined
    temp = *ptrA;
    // *ptrA = 1, *ptrB = 2, temp = 1
    *ptrA = *ptrB;
    // *ptrA = 2, *ptrB = 2, temp = 1
    *ptrB = temp;
    // *ptrA = 2, *ptrB = 1, temp = 1
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Seriously?

    Suppose I want to exchange the contents of two cups. One has coffee, the other has tea. I begin by pouring the tea into the coffee...

    Is it that hard to grasp the need for a third cup?

  4. #4
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    i would also recommend moving the printf statements that show the swapped values. it wont change anything in the situation now, but it helps to show that a and b in main have actually changed.
    for example, if you did a program like this in the future and somehow it changed the variables in your function so it seemed to work, but in fact maybe something is wrong and the variables you meant to change in main have stayed the same.

    so what i would do is move the 2 printf statements in swap and put them in the main function after calling swap but of course before the system("pause") command.

    just a suggestion

  5. #5
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    You could also use bitwise XOR:

    Code:
    *ptrA ^= *ptrB;
    *ptrB ^= *ptrA;
    *ptrA ^= *ptrB;
    If you don't know what it is, look it up on google. If this is an assignment, you should definitely use XOR, it'll give you some extra credit for sure.

  6. #6
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    i doubt it would give extra credit--it would look like an attempt from someone who was confused. it looks messy and, since ive never used bitwise operators but would consider myself experienced, it looks confusing when what they are trying to do is actually simple. i think it over complicates things.

    again, just my thoughts.

  7. #7
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by IceDane View Post
    If you don't know what it is, look it up on google. If this is an assignment, you should definitely use XOR, it'll give you some extra credit for sure.
    XOR'ing two doubles... That's rich.

    I got my ass handed to me when I dared to mention the XOR trick on this forum. I mentioned it as a bit of trivia, not an actual SUGGESTION to use it. And here you are actually telling somebody to use it.

    You're setting him up for an awful embarrassment when the instructor asks how it works.

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    http://en.wikipedia.org/wiki/XOR_swap_algorithm

    It doesn't work if the two arguments are equal, so for correctness you would have to check for this first.

    Edit: Actually, the problem is if the arguments have the same address (aliasing).
    Last edited by robatino; 09-12-2007 at 02:26 PM.

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    It's also tough for compilers to optimize, or so I hear. Just use a temporary variable; there's no need to do otherwise with today's compilers. If the XOR method really is more efficient, the compiler will generate code that uses it.

    http://en.wikipedia.org/wiki/XOR_swap_algorithm

    [edit] Too late again. [/edit]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by brewbuck View Post
    XOR'ing two doubles... That's rich.

    I got my ass handed to me when I dared to mention the XOR trick on this forum. I mentioned it as a bit of trivia, not an actual SUGGESTION to use it. And here you are actually telling somebody to use it.

    You're setting him up for an awful embarrassment when the instructor asks how it works.
    Didn't notice it was doubles we were talking about.

    I told him to look it up before he used it, of course. There's nothing wrong with the XOR trick, it's faster and more efficient(Not that it really matters in this case), but it saves you extra x bytes of memory. Also, it is hard for the compiler to detect that you're swapping two variables.

    Robatino: Whether or not the variables have the same address is irrelevant - You're swapping the values stored at the addresses.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    I would suggest you actually try your XOR trick with both pointers pointing at the same address, just to see what you get.

    Still think it's a swap function?

    > but it saves you extra x bytes of memory
    You mean you trade code space for data space.
    With a temp, it's just 3 moves.
    Without, it's 3 moves and 3 ops.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Registered User
    Join Date
    Sep 2007
    Posts
    29
    thank you very much for the help dwks. yes i am about as novice as they come to C, which is why i didn't get the whole third variable needed the way my friend was trying to explain it to me. I'm trying to get my language skills better (to get a job in web design, the only language i know right now is html and very little c++ i did in high school 5 years ago).

    brewbuck, is it hard to grasp the concept of not being a dick? dwks and others answered my question with respect which i why i came here for help with coding, thanks again for the help in past/present/future yall.

  13. #13
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by mackieinva View Post
    brewbuck, is it hard to grasp the concept of not being a dick? dwks and others answered my question with respect which i why i came here for help with coding, thanks again for the help in past/present/future yall.
    I guess that was ruder than I was shooting for. But don't just turn your brain off because you're dealing with a computer. Too many people have a habit of doing that. When you want to exchange two items, be it variables or physical objects, it should be apparent that you need some "space" in order to do it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with project
    By chrisa777 in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2006, 05:01 PM
  2. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  3. Replies: 2
    Last Post: 03-07-2002, 10:14 AM