Hi guys, I am trying to program some sample tasks with pointers. Below is the step by step instructions that I have to follow. I am having trouble at step 10 which is to swap the values of 2 variables using pointers. please help, I have tried almost anything out of the book and can't still figure it out.
1. Create to integer variables named x and y
2. Create an int pointer named p1
3. Store the address of x in p1
4. Use p1 to set the value of x to 99
5. Using cout, display the value of x
6. Using cout and the pointer p1, display the value of x
7. Store the address of y into p1
8. Use p1 to set the value of y to -300
9. Create two new variables: an int named temp, and an int pointer named p2
10. Use temp, p1, and p2 to swap the values in x and y
11. Write a function with the following signature: void noNegatives(int *x). The function should accept the address of an int variable. If the value of this int is negative it should set it to zero
12. Invoke the function twice: once with the address of x as the argument, and once with the address of y
13. Use p2 to display the values in x and y
14. Create an int array with two elements. The array should be named a
15. Use p2 to initialize the first element of a with the value of x
16. Use p2 to initialize the second element of a with the value of y
17. Using cout, display the address of the first element in a
18. Using cout display the address of the second element in a
19. Use p1, p2, and temp to swap the values in the two elements of a
20. Display the values of the two elements.
#include "stdafx.h"
#include <iostream>
void noNegatives(int *x);
using namespace std;
int main()
{
//1
int x, y;
//2
int *p1;
//3
p1 = &x;
//4
*p1 = 99;
//5
cout << "the value of x is " << x << endl;
//6
cout << " the value of x using *p1 is " << *p1 << endl;
//7
p1 = &y;
//8
*p1 = -300;
//9
int temp, *p2;
//10 I learned how to swap values using 3 variables.but, can't seem to do it
// with pointers.
p2 = &temp;
*p2 = *p1;
temp = x;
x= y;
y= temp;
cout << x << endl;
cout << y << endl;
//11 this fn is supposed to set pointers to 0 if they have negative numbers.
noNegatives(p1);
noNegatives(p2);
// apparently, *p2 comes out the same regardless of the x and y.
cout << "y value is" << *p2 << endl;
cout << "x value is" << *p2 << endl;
//14
int a[2];
//15 i think this is wrong since i am not supposed to assigned a new int
//to the pointer. please help me on this too.
p2 = &a[0];
*p2 = 99;
//16
p2 = &a[1];
*p2 = *p1;
//17 & 18
cout << "the first element is " << a[0] << endl;
cout << "the second element is " << a[1] << endl;
//19 and 20
p2 = &temp;
*p2 = 99;
a[1] = temp;
p2 = &temp;
*p2 = *p1;
a[0] = temp;
cout << "the first element is " << a[0] << endl;
cout << "the second element is " << a[1] << endl;
system("pause");
return 0;
}
void noNegatives(int *x)
{
if (*x < 0)
{
*x = 0;
}
}