Take the 2-minute tour ×

I am trying to learn C++ and trying to write a code for a simple hash table like following structure:

array[0][0] array[0][1] array[0][2]
key 1        value 1      value 2

array[1][0] array[1][1] 
key 2        value 3     

array[2][0] array[2][1] array[2][2]
key 3        value 4      value 5

means Array of Dynamic Arrays. Now, I can't understand how to define the array like that ?

Any help on this will be grateful.

share|improve this question
std::vector<std::vector<int>> ? –  Blue Moon Nov 2 '12 at 8:58

4 Answers 4

up vote 1 down vote accepted

If you really did need to create a dynamic array of dynamic arrays you would have to do it using the new keyword for both arrays. For example:

// an array of int pointers... each points to the start of an array
int** arrays = new int*[10]; 
arrays[0] = new int[99]; // populate the first element of the array of arrays
arrays[1] = new int[47]; // arrays don't have to be the same size.

Of course I highly recommend NOT doing this. You have to then remember to use delete[] on each member of arrays and on arrays itself.

Really you should use the built in std::vector type for this. It is why it is there (I voted for the other answers!).

Just as a note, this is not contiguous memory either. Also if you do want the member arrays to be the same size you could allocate their memory in a for loop.

share|improve this answer
thanks a lot. I really want what answer you have provided. –  alessandro Nov 2 '12 at 10:14

This is old, and I'm sure I'm not writing anything answer posters don't know in the back of their minds, but OP looks like he's doing an assignment for homework. My homework requires me to write out routines with out using any STL resources. In that case the only possible answer here is the first one. Homework in the beginning isn't about efficiency, it's demonstrating use of lesson material.

Unfortunately much of the time what they want you to demonstrate is never illustrated in the lessons. Which brings OP's like this one to dig the web for hard to find reference. Hard to find because nobody really does it the way they are required to do it.

I followed this link because the title led me to believe I would find resource for a static array of dynamic arrays. So I will post that application incase anyone else is looking for that reference.

int main() {

  int* time[2];
  int userInp;

  userInp = 5;

  time[0] = new int[userInp];

  time[0][1] = 6;

  cout << time[0][1];

  delete time[0];

  return 0; 


share|improve this answer

In C++ you would use a std::vector<T> and nest two of them in order to get a 2D array.

 std::vector<std::vector<my_type>> vec;
 std::vector<my_type> v;
share|improve this answer
Vector of vectors isn't exactly a "2D array", as it's not contignuous in memory –  Kos Nov 2 '12 at 9:24

Create a vector <vector <T> >.

For example

vector <vector <string> > array;

vector <string> temp;
share|improve this answer

Your Answer


