forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
12 additions
and
33 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,47 +1,26 @@ | ||
//! @Alan | ||
//! @Yue Wang | ||
//! | ||
//! Exercise 6.22: | ||
//! Write a function to swap two int pointers. | ||
//! | ||
|
||
|
||
|
||
#include <iostream> | ||
#include <string> | ||
#include <vector> | ||
|
||
using namespace std; | ||
void swap(int*& lft, int*& rht) | ||
{ | ||
auto tmp = lft; | ||
lft = rht; | ||
rht = tmp; | ||
} | ||
|
||
//! | ||
//! @brief swap_ptr | ||
//! @note a pointer is an object, so it can be referenced to using &. | ||
//! int* &_p1 means _p1 is a reference to an int pointer. | ||
//! | ||
void swap_ptr(int* &_p1, int* &_p2); | ||
int main() | ||
{ | ||
int a, b; | ||
int *p1=&a, *p2=&b; | ||
|
||
cout<<"Plz enter:\n"; | ||
while(cin>>a>>b) | ||
{ | ||
p1=&a, p2=&b; //make sure p1-->a and p2-->b, otherwise funny things will happen | ||
//and look like the swap_ptr doesn't work. | ||
|
||
swap_ptr(p1, p2); | ||
cout<<*p1 | ||
<<" " | ||
<<*p2 | ||
<<"\n"; | ||
} | ||
int i = 42, j = 99; | ||
auto lft = &i; | ||
auto rht = &j; | ||
swap(lft, rht); | ||
std::cout << *lft << " " << *rht << std::endl; | ||
|
||
return 0; | ||
} | ||
|
||
void swap_ptr(int* &_p1, int* &_p2) | ||
{ | ||
int *temp = _p1; | ||
_p1 = _p2; | ||
_p2 = temp; | ||
} |