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?
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?
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.