Pointers and Swap

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • CisFun
    New Member
    • Nov 2008
    • 1

    Pointers and Swap

    Ok, so I've successfully written my swap application but now i'm trying to rewrite it so i'm using pointers to pass the address of the argument to the function. I'm going to have the swapping performed in the main function after calling the swap function.

    Code:
    #include <iostream.h>
    
    void main()
    
    {
    
    void swap(int x, int y);
    
    int first_num = 10;
    
    int second_num = 50;
    
    cout << "\nThe value of first_num is " << first_num << endl
    
    << "The value of second_num is " << second_num << endl;
    
    swap(first_num, second_num);
    
    cout << "\nThe value of first_num is now " << first_num << endl
    
    << "The value of second_num is now " << second_num <<
    
    endl;
    
    }
    
    void swap(int x, int y)
    
    {
    
    int local_int;
    
    local_int = x;
    
    x = y;
    
    y = local_int;
    
    cout << "\nIn the function first_num is " << x << endl
    
    << "In the function second_num is " << y << endl;
    
    }
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    The code you posted does not compile. If you want help with compiler errors you are getting, please post them here. Once you have this code working, what is your question about pointers? If you have specific questions about pointers or code that you have written, you can post them here, but what you have posted is not an answerable question.
    Thanks.

    Comment

    • arnaudk
      Contributor
      • Sep 2007
      • 425

      #3
      Originally posted by CisFun
      Ok, so I've successfully written my swap application but now i'm trying to rewrite it so i'm using pointers to pass the address of the argument to the function.
      So then your function will look like
      void swap(int* a, int* b);
      and it dereferences the pointers and swaps the integers they point to.
      EDIT: Sorry, boxfish is right, upon looking at your code, I also see some glaring errors which you'd better fix first. Even when you get it to compile, your swap function won't work. You need to pass pointers or references to your swap function, don't call by value as you'll create local variables x and y in your swap function which will have no bearing on first_num and second_num in main. Also, it's <iostream> not <iostream.h> and declare your swap function outside the body of main() and main() returns int not void and etc.

      Comment

      Working...