Dynamic array of arrays

Hello people,

like the title says, I need to know how to create a series of dynamic arrays using pointers, the user should decide how many arrays to be created, then again the user will decide the size of these arrays, can somebody help

PS. I know how to create a dynamic array

Thanks Mac
std::vector<std::vector<T> > dynamic_array_of_dynamic_arrays;
Thanks helios,

aaaam can you give me a little explanation, I'm kinda beginner here

Mac
Which part don't you understand?
He wants to use pointers...


Remember, that you create a dynamic array like this (substitute your type of choice for int)
1
2
unsigned width = 120;
int* dynamic_array = new int[ width ];

The variable 'dynamic_array' can now be treated as an array of 120 integers.

However, you want an array of these arrays. That is to say, you want a containing array whose elements are the same type as the one-dimensional dynamic array we just created. That is:
1
2
unsigned height = 5;
(int*)* dynamic_array_of_dynamic_arrays = new (int*)[ height ];
The type can be abbreviated as simply int**.

Of course, you will also have to create each sub-array:
1
2
for (unsigned h = 0; h < height; h++)
  dynamic_array_of_dynamic_arrays[ h ] = new int[ width ];


Notice how the size of the arrays is dependant on the variables width and height. That should be enough to get you going.

Oh, also, don't forget that you must also delete[] everything you allocate with new[]. Do that in the reverse order you created them
1
2
3
for (unsigned h = 0; h < height; h++)
  delete[] dynamic_array_of_dynamic_arrays[ h ];
delete[] dynamic_array_of_dynamic_arrays;

Please use an appropriate name for your dynamic array of dynamic arrays... the one we provided is just because we have no idea what you are going to do with this.

Good luck!
Thanks a ton Duoas,

But I don't see the dynamic part of the arrays if the width and the height are already given constant values, I was thinking is it possible that the user get to input the values of width and height?

and then after doing that I will make a for loop to let the user start filling in the values which are to be put in each cell

what do you think

Mac
Topic archived. No new replies allowed.