0

I have a an array int matrix[10][10] as well as other arrays with similar size which is declared before the prototype functions and main function. This 2d array is used by all of the functions. However, I need my program to have a function that asks the user the size of the matrix he wants. So, it's gotta be something like this: int matrix[ROWS][COLUMNS]. I know for sure that I can't place the declare the array inside the main function since this array is used by all the other functions. How do I declare this kind of array?

Ram24
  • 43
  • 1
  • 9
  • 3
    possible duplicate of [How do I declare a 2d array in C++ using new?](http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new) – Cory Kramer May 21 '15 at 14:31
  • 1
    Declaration, definition and initialization are three different things. You can declare and define the array in the global scope yet initialize it in main – KABoissonneault May 21 '15 at 14:34
  • 2
    You cannot declare a array like that if the dimensions are not compile-time constants, https://stackoverflow.com/questions/1887097/variable-length-arrays-in-c – Benjamin Bannier May 21 '15 at 14:40
  • Any reason not to use [vector](http://en.cppreference.com/w/cpp/container/vector)? – sam May 21 '15 at 14:43

1 Answers1

2

First of all, it is impossible to declare an array with variable sizes, as they are not legal in C++ (although they are legal in C). So you're out of luck here. Second, you want the declaration before main. Hence, you have to use either

  1. A dynamic array, defined globally like int** matrix; and initialized in main() as

    matrix = new int*[ROWS];
    for(size_t i = 0 ; i < ROWS; ++i)
        matrix[i] = new int[COLS];
    

    then you'd have to release its memory at the end of the day

    for(size_t i = 0; i < ROWS; ++i)
        delete[] matrix[i];
    delete[] matrix;
    

or

  1. A standard container like std::vector<>

    std::vector<int> matrix; // defined globally
    

and in main() reserve memory for it, like

matrix.reserve(ROWS*COLUMNS); // reserve memory for M rows

Then you'd need to play around with the indexes, so you can map from pairs of indexes to 1D index, i.e. the "logical" element [i][j] is represented by the index i * COLS + j in matrix.

Of course, you could have used a std::vector<std::vector<int>>, however this approach is faster since the memory is guaranteed to be contiguous (same applies to the first example, where you could have used an int* instead).

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252