This program is to simply practice the function parameter type called by pointer
ID: 3631516 • Letter: T
Question
This program is to simply practice the function parameter type called by pointers. A function SwapWithPtr() could be defined as:void SwapWithPtr(int* ptr1, int* ptr2);
You have to call it twice.
Define integer variables n1 and n2. Receive input values and call SwapWithPtr() to swap the values in n1 and n2. Output n1 and n2 to verify
Define pointer variables p1 and p2. Make p1 and p2 point to the addresses of n1 and n2 individually. Call SwapWithPtr() to swap the values back with p1 and p2. Output to verify
Think of how to pass an integer argument and how to pass a pointer argument to SwapWithPtr(). When test your code, the result should be like this:
=============================================================================
Enter n1 and n2: 111 222
After the first swap call using n1 and n2:
n1=222, n2=111
After the second swap call using p1 and p2:
n1=111, n2=222
*p1=111, *p2=222
Press any key to continue . . .
Explanation / Answer
please rate - thanks
#include <iostream>
using namespace std;
void SwapWithPtr(int* ptr1, int* ptr2);
int main()
{
int n1,n2;
int* p1;
int* p2;
cout<<"enter n1 and n2: ";
cin>>n1>>n2;
SwapWithPtr(&n1,&n2);
cout<<"After the first swap call using n1 and n2: ";
cout<<"n1= "<<n1<<", n2= "<<n2<<endl;
p1=&n1;
p2=&n2;
SwapWithPtr(p1,p2);
cout<<"After the second swap call using p1 and p2: ";
cout<<"n1= "<<n1<<", n2= "<<n2<<endl;
cout<<"*p1= "<<*p1<<", *p2= "<<*p2<<endl;
system("pause");
return 0;
}
void SwapWithPtr(int* ptr1, int* ptr2)
{int p;
p=*ptr1;
*ptr1=*ptr2;
*ptr2=p;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.