-3

I am new to C++. I don't quite understand why this code does not work. What does this code have to do with stack-dynamic variable? Thanks for your help.

int twice(int x)
{
    int *y;
    *y = x * 2;
    return *y;
} 

1 Answers1

0
int *y;
*y = x * 2;

is not correct because y points nowwhere, not into an allocated memory. It is undefined behavior. After this line of code your program is completely unpredictable and you cannot assume anything about its behavior.

You need to allocate the memory first using new or malloc and assign x*2 to it or pass an address to assign y into, i.e:

int *y = new int( x * 2);

Example:

int main() {

    int x = 4;
    int *y = new int( x * 2);
    cout << x << "," << *y;
    delete y;

    return 0;
}

Side note: this is dangerous to return a pointer to memory allocated in function because this might become unclear who and when is responsible for freeing allocated memory. In your particular case there is absolutely no apparent reason for dynamic allocation by the way.

4pie0
  • 29,204
  • 9
  • 82
  • 118