Re: Stroustrup 5.9, exercise 4 (page 105)
On Mar 31, 7:28 pm, Manuel T <man...@t.gov> wrote:
Logic errors lie in swap_X functions. Do a little trace on paper and you'll
discovery why this stuff don't work.
Hint: you are working with references/pointers(i.e. memory addresses) and
not with values.
ok forget about references for the moment. just think about Pointers
only. i came up with this BUGGY solution. it has semantic-BUG. i can
not find out "why it has a bug" except that i have a lot of
*headache* after banging my head with it for 2 hours:
--------- PROGRAMME ------------
/* Stroustrup, 5.9 exercise 4
STATEMENT:
write a programme that swaps 2 integers. solve it
using 1st with pointers and then references.
METHOD:
1.) asks the user to input 2 integers
2.) swaps the value using pointers,
prints 2 statements to show what it is doing
3.) prints the SWAPPED values
4.) swaps the vale sagain using References
5.) so after swapping 2 times we get the original input values.
*/
#include<iostream>
void swap_p(int* x, int* y);
void swap_r(int& x, int& y);
int main()
{
using std::cout;
using std::cin;
using std::endl;
int i;
int j;
cout << "Enter 1st integer: ";
cin >> i;
cout << "enter 2nd integer: ";
cin >> j;
cout << "i = " << i << '\t'
<< "j = " << j << endl;
int* pi = &i;
int* pj = &j;
cout << "pi = " << &i << '\t'
<< "pj = " << &j << endl;
swap_p(pi, pj);
cout << "\nvalues swapped using Poiners\n"
<< "pi = " << pi << '\t'
<< "pj = " << pj << endl;
cout << "VALUES: "
<< "i = " << i << '\t'
<< "j = " << j << endl;
return 0;
}
void swap_p(int* x, int* y)
{
int** tmp_x = &y;
int** tmp_y = &x;
std::cout << "tmp_x = " << tmp_x << '\t'
<< "tmp_y = " << tmp_y << std::endl;
x = *tmp_y;
std::cout << "------------------------------\n";
std::cout << "x = " << x << "\ty = " << y << '\n';
y = *tmp_x;
std::cout << "x = " << x << "\ty = " << y << '\n';
std::cout << "------------------------------\n";
}
--------- OUTPUT -----------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra swap_p.cpp
[arch@voodo tc++pl]$ ./a.out
Enter 1st integer: 3
enter 2nd integer: -3
i = 3 j = -3
pi = 0xbfc4c320 pj = 0xbfc4c31c
tmp_x = 0xbfc4c314 tmp_y = 0xbfc4c310
------------------------------
x = 0xbfc4c320 y = 0xbfc4c31c
x = 0xbfc4c320 y = 0xbfc4c31c
------------------------------
values swapped using Poiners
pi = 0xbfc4c320 pj = 0xbfc4c31c
VALUES: i = 3 j = -3
[arch@voodo tc++pl]$