0

I don't know why my function doesn't work. I mean I want my function to return a bidimentional array long double[][], but there are errors in my code. Can anyone tell me the correct form to return a bidimentional array in a function?

long double[][] hilbert(int n){
    long double A[n][n];

    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            A[i][j]=0.0;
        }
    }
    return A;
}
  • [Does this help](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048)? – PaulMcKenzie Nov 23 '20 at 05:49

2 Answers2

1

I don't know why my function doesn't work

It doesn't work because you are trying to return an array. In C++, return type of a function cannot be an array (regardless of number of dimensions).

It also doesn't work because you're trying to specify the size of array dimension using a value that is not compile time constant. That is not allowed in C++ either.

One simple solution is to return a std::vector containing std::vectors. There are however more efficient ways of representing 2D matrices such as a single dimensional vector where rows are one after the other.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

you're specifying the size of array dimension using a value that is not compile time constant .

also the array you are making in the function will be created in the stack part of memory and when you go outside of the function scope the memory allocated by the array will be freed so you cannot return that.

Probably the best way to solve these problems is too create a dynamic array, this way the dimension size can be specified in runtime and you can also return that from the function and the memory will not be freed until you free it manually .

long double** hilbert(int n){

    // Making an array of pointers
    long double **A = new long double*[n];

    for (int i = 0; i < n; i++)
        // create an array of size n and put the
        // first element address to A[i]
        A[i] = new long double[n];

    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            A[i][j]=0.0;
        }
    }

    return A; // Return the array
}

int main() {

    // Creating array using the fucntion we've
    // just created .
    long double** array = hilbert(10);

    // Use the array
    std::cout << array[0][1] << std::endl;

    // free the memory when you're done ...

    return 0;
}