How write a method that return a array of int?

I learn that a method can receive an array

1
2
3
void my_method(int**matrix){
...
}


But, and to return an array?

I tried

1
2
3
4
int** my_method(){
    int m[10][10];
    return m;
}


but this do not work.
Last edited on
First, an array created this way is not technically the same type as int**, so that shouldn't even compile.

Additionally, this will not work because when you create the array m[10][10], you are creating it on the stack, within the scope of my_method(). Once my_method() ends, any local variables will go out of scope (no longer exist). You can create the array on the heap using the new operator as follows:

1
2
3
4
5
6
7
8
9
10
int ** my_method()
{ 
    int **m = new int*[10];
    for (int i=0; i<10; i++)
    {
        m[i] = new int[10];
    }

    return m;
}


However, this is generally not a good idea, since you must remember to use delete later in your code, or you will have a memory leak. Creating the array outside the method and passing it as an argument is generally a better way of doing things.

Arrays and dynamic memory are usually painful for beginners, so I'd suggest you read:

http://cplusplus.com/doc/tutorial/arrays/

... before venturing further.
You'll want to check out the articles database as well. Here are a couple and there are probably more. My first question is always "why do you want to return an array from a function in the first place"? What is the function in question really doing? If the function has special knowledge required for initialization of the array then it could be reasonable to use it for filling an array. Either way returning an array is never a good idea in my mind. There are too many potential problems such as memory leaks, undefined behavior, and so forth.

Take a look at this. Part II talks about returning arrays and gives examples of why it is a bad idea to do that. Even if you return a sequence container by value you are still going to have to copy the data at least once.
http://cplusplus.com/forum/articles/20881/

For multidimensional arrays here is another with some specific ideas since the previous article doesn't really go into array dimensions. It is so easy to create an array I do not know why one would need a function for creating an array. I would think that it makes more sense to create an array in place and possibly use a function for filling it or processing the data.
http://cplusplus.com/forum/articles/7459/



Topic archived. No new replies allowed.