How do I get the values of \'*numPtr\' and \'num\' in main to be 10 using a poin
ID: 3854191 • Letter: H
Question
How do I get the values of '*numPtr' and 'num' in main to be 10 using a pointer and having a void function 'addFive()' that doesn't return a value?
***** BELOW - pointerPlay.cpp. ************
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
void addFive(int);
void addFive(int num)
{
cout << "The value of num in function: " << num << endl;
num += 5;
cout << "The value of num in function after adding 5: " << num << endl;
}
int main(int argc, char const *argv[]) {
int num = 5;
int* numPtr = #
addFive(*numPtr);
cout << "The value of numPtr in main: " << numPtr << endl;
cout << "The value of *numPtr in main: " << *numPtr << endl;
cout << "The value of num in main: " << num << endl;
return 0;
}
Explanation / Answer
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
void addFive(int);
void addFive(int *num)/*making the num Parameter variable as pointer type ,to receive the address of numptr variable from main*/
{
cout << "The value of num in function: " << *num << endl;/*To get the value ,we will deference num by using *(asterisk) operator */
*num += 5;/*Asterisk operator deference the value stored in num pointer variable,hence while doing addition we will use * operator to add 5 to it */
cout << "The value of num in function after adding 5: " << *num << endl;
}
int main(int argc, char const *argv[]) {
int num = 5;
int* numPtr = #
//addFive(*numptr);/*If we will not comment this line, it will give compilation error.It is because in the original code which you provided ,the argument received by addFive(int num) was mismatching with the argument passed to that function.Argument passed is of pointer to pointer type where as the type which that function is expecting is normal variable*/
addFive(numPtr);/*Argument passed will be of pointer type,so that all the changes made by that function will be automatically reflected without even returning any value */
cout << "The value of numPtr in main: " << numPtr << endl;
cout << "The value of *numPtr in main: " << *numPtr << endl;
cout << "The value of num in main: " << num << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.