Hello, i have a simple question about pointers... The code that goes with the problem is:

int* getPtrToArray(int& m)
    {
        int anArray[5] = { 5, 4, 3, 2, 1 };
        m = 5;
        return anArray;
    }

    int main()
    {
        int n;
        int* ptr = getPtrToArray(n);
        for (int i = 0; i < 5; i++)
            cout << ptr[i] << ' ';
    }

What the program is trying to do is simply display "5 4 3 2 1". However, there is a problem within the getPtrToArray function that prevents it from doing this. It asks how to change the getPtrToArray function in order for it to display the numbers correctly. I have a fairly good grasp (i think) on why it doesnt work: basically, since myArray is declared within the getPtrToArray function, it cant pass the whole array back to int main and instead just passes myArray[0] back... My only problem is i have no idea what change i could make to the getPtrToArray function to fix this. I know that if myArray was declared within int main, and the point "ptr" was declared to be equal to myArray, the program would function as intended BUT since im only allowed to change the top function, i dont know what to do really...

Any help would be much appreciated.

The reason is that anArray is local to the scope of the function. So by the time that you use it with the ptr is it out of scope. Old compilers, use to allow this (without warnings), and no end of mayhem followed.

To get round this, you can (a) declare it on the heap int* anArray=new int[5]; .. populate ...

or (b) declare it static static int* anArray={1,2,3,4,5}; If you use option (a), you are responsible to deleting the memory!

thank you, part b worked flawlessly

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.