My professor had me copy and paste the code below she wrote, and it kept on giving me bugs.
By running her program, the output was 1 for any value.
Logically, I understand how the function should return the address and in the main it prints the value of it. Theoretically, that is.
So here's what I tried so far:
Simply removing the statement p = cube(&n) and replacing with:
std::cout << "Cube of " << n << " is " << cube(&n) << std::endl;
This worked.
In order to solve the "local variable" error, I made 'result' a global variable.
In cube(), I did:
int *cube(int *number) { int result = (*number) * (*number) * (*number); int *newResult = &newResult; return newResult; }
...but it outputted 1 for any integer.
This is the code sample she shared.
#include <iostream>
int *cube(int *);
int main()
{
int n, *p;
std::cout << "Enter an int: ";
std::cin >> n;
p = cube(&n);
std::cout << "Cube of " << n << " is " << *p << std::endl;
return 0;
}
int *cube(int *number)
{
int result = (*number) * (*number) * (*number);
return &result;
}
According to her, the output of this program should be the cube of the inputted integer. For example, 3 in -> 27 out.