I have only started using C++ properly over the past few months and I’m realising that many of the features and aspects I took for granted in interpreted languages, are implemented in a much more complicated way in c++!
For example if you wanted to create a dynamic array in c# (as below) the .NET framework will do all the memory allocation and management for you and let you initialise an array of your chosen size at run time (when the size of the array cannot be determined at compile time)
int[] temp = new int[varName] //Where varName could be an integer given by the user
Another interesting point at this stage is that after c# initialises the array dynamicaly, for example with a dimension of 3. When you try and access temp[20] for example, the .net framework instantly detects you are breaching the size of the array and throws an “Out of bounds” exception. However in c++ (and this applies to static and dynamic arrays) accesing a position outside the array simply looks up in memory PAST the array and starts reading random data, not even necessarily from your application!
Anyway, to make a dynamic array in c++ we must follow 3 steps
- use the new keyword to initialise the array in memory
- ensure that the memory allocation for the array was successfull, catching the failure of this event
- delete the array from memory after use (as c++ will not dispose of it automatically)
The example below simply gets a number from the user and then initialises an array with the dimension the user has specified.
int mySize( 0);
cin >> mySize;
int myArray[] = new int[mySize];
if(myArray!=0)
{
//catch failure of array initialisation
}
else
{
//Work with array….
delete[] rain;
}












Array3d (size_t r, size_t c, size_t u) {
assert (r > 0 && c > 0 && u > 0);
rows_ = r;
cols_ = c;
ups_ = u;
data_ =new Array [rows_];
for (size_t i = 0; i < rows_; i++)
{ data_[i] =Array (cols_);
for (size_t j = 0; j < cols_; j++)
v_[i][j]=Array (ups_);
}
}
Hi,
Please Check the above declaration of three dimensionaal array using dynamic memory concetp, but it is not working, Can you what is the errot.
Munawar