pointers/loop

Sorry this is kind of a weird question
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  int* getPtrToArray(int& m)
    {
        int anArray[5] = { 5, 4, 3, 2, 1 };
        m = 5;
        return anArray;
    }

    void f()
    {
        int junk[100];
        for (int k = 0; k < 100; k++)
            junk[k] = 123400000 + k;
    }

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

This is designed to print 5 4 3 2 1. I know it doesnt, and I know how to fix it with a different for loop in main, but I am trying to figure out why this doesnt work and what effect f() has on the pointer. Since the pointer is technically pointing at anArray[0], why does the function f() mess it up?
You're returning the address of a local variable from getPtrToArray(). And the local variable of a function cease to exist when it returns.

Either use a static variable (I would only think of using this if the data in the array was fixed, in which case it would be better const)

1
2
3
4
5
6
7
int* getPtrToArray(int& m)
    {
        // static variables stay around when a function exits 
        static int anArray[5] = { 5, 4, 3, 2, 1 };
        m = sizeof(anArray)/sizeof(anArray[0]); // get the compiler to work out size for you
        return anArray;
    }


Or allocate memory on the heap with new, e.g. int* parray = new int[5];, copy your data into that array, and then return it. In this case you will need to delete the array after use (delete [] parray;).

Andy

(Actually, old local variables may lurk around a bit after a function returns, depending on what happens next in your program, so sometimes a program works ok for a while before dying. But you can't assume the values are valid as the compiler if free to reuse the memory for other purposes (e.g. another function call) whenever it want, after the function does out of scope.
Last edited on
The problem is with
1
2
3
4
5
6
  int* getPtrToArray(int& m)
    {
        int anArray[5] = { 5, 4, 3, 2, 1 };
        m = 5;
        return anArray;
    }

variable anArray is local and will be destroed when the function ends, so you returning pointer to deallocated memory. junk array will be created at the same place, where anArray was (this is how stack work). To get around this you need to create anArray in heap instead on stack. Like that:
1
2
3
4
5
6
  int* getPtrToArray(int& m)
    {
        int* anArray = new int[5]{ 5, 4, 3, 2, 1 };
        m = 5;
        return anArray;
    }

note, that you will need to manually delete allocated memory in this case
Last edited on
I see now, thanks for your help
Note that

int* anArray = new int[5]{ 5, 4, 3, 2, 1 };

is not valid C++03. So if you're compiler isn't up to C++11 it'll cause grief!

Andy
Topic archived. No new replies allowed.