0

I want to set the elements of a 2d array equal to zero but I want the array to be defined via variables. Afterwards, I would like to print this matrix. The solutions that I have found, for example here Initialize multidimensional array with zeros, work only when the matrix is defined as myArray[12][8], whereas I need them to be defined as

int n = 80; 
int m =100;
double myArray[n][m];

I had the same problem when I tried to implement a function that prints the 2d array. For example:

template <typename T, size_t N, size_t M >
void Print2D_dArray(T(&myarray)[N][M]){

    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            std::cout << myarray[i][j] << " ";
        }
        std::cout << std::endl;
    }
}//Print2D_dArray

When I passed a matrix like myArray[10][10] it would compile and print the array. When I use variables I am getting the error "template argument deduction/substitution failed".

Angelos
  • 169
  • 10
  • `double myArray[n][m];` is not standard c++. Does this answer your question? [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – 463035818_is_not_an_ai Jun 24 '20 at 12:46
  • 2
    If you want a run time sized array, what you want is a `std::vector`. If you want a 2d array, use a 1d `std::vector` and encapsulate it in a matrix class so you can fake that it has two dimensions. – NathanOliver Jun 24 '20 at 12:47
  • btw why do you **need** them to be defined like that? Thats not quite clear and if you can define it like that you could as well make `x` and `y` constant expressions. I suppose you actually want `int x = get_dimension_from_somewhere(); int y = get_dimension_from_somewhereelse();` – 463035818_is_not_an_ai Jun 24 '20 at 12:49
  • Does this answer your question? [how to pass an array with different sizes to my c++ function?](https://stackoverflow.com/questions/52323782/how-to-pass-an-array-with-different-sizes-to-my-c-function) or [when do we need to pass the size of array as a parameter](https://stackoverflow.com/questions/6638729/when-do-we-need-to-pass-the-size-of-array-as-a-parameter) – Melebius Jun 24 '20 at 12:50
  • Is it fast to get the values A[i][j] if I use ```std::vector```? – Angelos Jun 24 '20 at 12:58
  • @idclev463035818 Ok, so the user will define these sizes in the beginning of the simulation inside the main function and these will remain fixed during the run. No need for dynamically changing arrays. – Angelos Jun 24 '20 at 13:01
  • 1
    you need dynamic arrays when the size is not known at compile time, whether their size changes later or not. – 463035818_is_not_an_ai Jun 24 '20 at 13:02

1 Answers1

0

Template arguments are evaluated at compile time, so you could only use const variables. How about

template <typename T>
void Print2D_dArray(T &myArray[][], size_t N, size_t M)

{ ... }

Tobi
  • 76
  • 5