1

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.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Quirk
  • 1,305
  • 4
  • 15
  • 29
  • 5
    C or C++? Choose one. – chris Oct 06 '13 at 15:56
  • If you choose C++ why don't you have a look at STL containers like std::vector? – hamon Oct 06 '13 at 16:01
  • 1
    One question per post please. No one gets confused and everybody's happy. You have two separate, unrelated questions. Please consider two separate posts. – n. m. could be an AI Oct 06 '13 at 16:01
  • @n.m. Actually, one can write the solution in a nice neat matrix :P –  Oct 06 '13 at 16:10
  • This is not the data structure you are looking for. What is the real problem you are trying to solve? – Eric Postpischil Oct 06 '13 at 17:14
  • @EricPostpischil The real problem used 2D arrays and Memoisation. – Quirk Oct 08 '13 at 17:22
  • voted as "unclear what you're asking": I think he is asking for a jagged array (i.e. each row is able to be a different length), which is not possible using array syntax in C. And if he is not asking for jagged, then just `int arr[n][k]`. – M.M Nov 03 '14 at 07:03

2 Answers2

4

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>> 
  • @MSalters: if you suggest the use of `vector`, you may as well add `int arr[n][k];`. –  Oct 06 '13 at 19:58
  • The place where I required this actually used 2D arrays and Memoisation. – Quirk Oct 08 '13 at 17:20
2

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];
Rivasa
  • 6,510
  • 3
  • 35
  • 64