Search code examples
c++carraysloopsvariable-length-array

How to make a program declare variable number of indefinite size arrays


This might sound crazy but I was wondering if it is possible to make a program declare n number of arrays of the type array[] in a loop using C/C++. For example, sample this pseudo-code:

input int _n_  

run loop for _n_ times such that:  
declare _array1[]_  
declare _array2[]_  
.  
.  
declare _array'n'[]_ 

So the problem here is two-fold:
- Declare variable length arrays
- Declare a variable number (i.e. n number of) such arrays.


Solution

  • The truth table:

    task        / language         | C                   | C++
    -------------------------------+-----------------------+------------------------
    Declare variable length arrays | Use VLAs            | not possible without
                                   |      int arr[n];    | non-standard extensions
                                   |                     | but use std::vector<T>
    -------------------------------+---------------------+--------------------------
    Declare a variable number      |  not possible but   | not possible but use
    (i.e. n number of) such arrays |  use int arr[n][k]; | vector<vector<T>>