Change a variable in main from another function.
What to build
A function that receives an address.
Requirements
- Write
void add_one(int* p). - Do not change
main.
Input
One whole number.
Output
One number.
Constraints
The number is from -1000 to 1000.
Example
Input:
4
Output:
5
Why it works
The function receives the address of the variable, so writing through it changes the original.
Examples
Example 1 · Input
4
Expected output
5
Example 2 · Input
-1
Expected output
0
Hints
Hint 1
A pointer parameter is written int* p.
Hint 2
Write through it with *p.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
void add_one(int* p) {
*p = *p + 1;
}
int main() {
int n;
cin >> n;
add_one(&n);
cout << n << endl;
return 0;
}