Return an Array from a Function

This is part of my Wumpus Hunt program. Suggestions were to clean up the main() part of the program by creating functions. I am working on that and ran into this difficulty (for me). The functions that relate to the rooms of the game need to return an array. I searched this topic and found that it is NOT AT ALL a clear and simple affair to have a function return an array in C++.

The clearest explanation I have seen so far is to create an array in heap memory and then have the function return a pointer to the first element of that array. A person said that a stack memory array can't be used because it will be destroyed when it goes out of scope at the end of the function.

This pointer business makes sense because this exercise is in the chapter on pointers, heap memory, arrays/vectors, and constructors/destructors.

Here is what was given as the correct way to return an array. Is that so?
1
2
3
4
5
6
7
int foo(int n){
    int* ptr = new int[n];
    for (int i = 0; i < n; i++) {
        ptr[i] = 2*i;
    }
    return ptr;
}


If that is correct, my next question is will it also work for a 2 dimensional array? I am using 2D arrays in my code. Is the first element of a 2D array [0][0]? Will a pointer point to ptr[0][0] in the following example?
1
2
3
4
5
6
7
8
9
int foo(int n, int m){
    int* ptr = new int[n][m];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            ptr[i][j] = 2*i + 4*j;
        }   
    }
    return ptr;
}

Thanks in advance.
Here is what was given as the correct way to return an array. Is that so?
almost.. it is supposed to be a int*foo(..., since you want to return an int*.

If that is correct, my next question is will it also work for a 2 dimensional array?
no, not like that.
That would be
1
2
int** ptr = new int*[m];
for(int i = 0; i < m; i++) ptr[i] = new int[n];

but really, see http://www.cplusplus.com/forum/articles/17108/

generally, what you're doing isn't very good. if you allocate an array in a function, you are very likely to forget to delete it. it would be better to use vectors.
Topic archived. No new replies allowed.