Returning a pointer of a local variable C++

Use the new operator

int * count()
{
    int myInt = 5;

    int * p = new int;
    *p = myInt;

    return p;
}

As pointed out in other answers this is generally a bad idea. If you must do it this way then maybe you can use a smart pointer. See this question for how to do this What is a smart pointer and when should I use one?


You could use smart pointers.

For example:

unique_ptr<int> count()
{
   unique_ptr<int> value(new int(5));
   return value;
}

Then you can access the integer as follows:

cout << "Value is " << *count() << endl;

You can do this by making the variable static:

int* count()
{
    static int myInt = 5;
    return &myInt;
}

It is an error to return a pointer to a local variable. x points to a variable allocated on the heap:

link x = new node(a[m]);
Thus x isn't pointing to a local variable.

The reason that returning a pointer to a local variable is an error is that such a variable exists for only as long as the function is active (i.e. between it is entered and exited). Variables allocated on the heap (e.g. with the use of the new operator) exist until they are deallocated (e.g. with the delete operator).