Question

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.

Was it helpful?

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>> 

OTHER TIPS

The way I understand it, if you want more than one array, couldn't you just use a 2D array? This of course means you don't have the variable length of an array, but you can have a variable amount of arrays with the same length.

Then you have this:

int n;
int array[n][length];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top