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?

Leave a Comment