-2

Possible Duplicate:
How do I best handle dynamic multi-dimensional arrays in C/C++?

I am developing an application. In that i need to declare multidimensional array dynamicly. with dynamic array size and values i want ot assin to it. Pls some one help me on this.

Advance Thanks

Community
  • 1
  • 1
Ibrahim
  • 1
  • 1

1 Answers1

0

It depends on how "dynamic" you want it.

One way to do it is:

const size_t outerSize = 15;
const size_t innerSize = 20;

int* arr = new int[outerSize * innerSize];

// To access an item, multiply the row index by the "width", and add the column index
arr[innerSize * 5 + 7] = 13;

// When done with the array:
delete[] arr;

The problem with this solution is that you have to be very careful to make sure that you call delete[] array;, even if an exception gets thrown.

If you don't want to worry about memory management, and you can be careful not to make a jagged arrays (or are okay with jagged arrays), then you can use:

std::vector<std::vector<YourType> >

You can initialize it with a specific size like this:

const size_t outerSize = 15;
const size_t innerSize = 20;

std::vector<YourType> initalRow(innerSize);
std::vector<std::vector<YourType> > multiDimArray(outerSize, initalRow);

You can also initialize it with a default pre-populated value:

const size_t outerSize = 15;
const size_t innerSize = 20;

YourType initialValue;
initialValue.ExampleValue = 7;
std::vector<YourType> initalRow(innerSize, initialValue);
std::vector<std::vector<YourType> > multiDimArray(outerSize, initalRow);

Just like any multi-dimensional array, the easiest way to populate it is going to be in two loops:

const size_t outerSize = 15;
const size_t innerSize = 20;

std::vector<YourType> initalRow(innerSize);
std::vector<std::vector<YourType> > multiDimArray(outerSize, initalRow);

for(size_t i = 0; i < outerSize; ++i)
{
  for(size_t j = 0; j < innerSize; ++j)
  {
    multiDimArray[i][j].ExampleValue = i * j;
  }
}
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183