By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,935 Members | 1,273 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,935 IT Pros & Developers. It's quick & easy.

Pointers and Swap

P: 1
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.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream.h>
  2.  
  3. void main()
  4.  
  5. {
  6.  
  7. void swap(int x, int y);
  8.  
  9. int first_num = 10;
  10.  
  11. int second_num = 50;
  12.  
  13. cout << "\nThe value of first_num is " << first_num << endl
  14.  
  15. << "The value of second_num is " << second_num << endl;
  16.  
  17. swap(first_num, second_num);
  18.  
  19. cout << "\nThe value of first_num is now " << first_num << endl
  20.  
  21. << "The value of second_num is now " << second_num <<
  22.  
  23. endl;
  24.  
  25. }
  26.  
  27. void swap(int x, int y)
  28.  
  29. {
  30.  
  31. int local_int;
  32.  
  33. local_int = x;
  34.  
  35. x = y;
  36.  
  37. y = local_int;
  38.  
  39. cout << "\nIn the function first_num is " << x << endl
  40.  
  41. << "In the function second_num is " << y << endl;
  42.  
  43. }
  44.  
Nov 9 '08 #1
Share this Question
Share on Google+
2 Replies


boxfish
Expert 100+
P: 469
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.
Nov 10 '08 #2

100+
P: 424
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.
Nov 10 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.