alessandro alessandro - 1 year ago 131
C++ Question

How to create Array of Dynamic Arrays in C++

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download