unknown Facts to know about 2D array

Two Dimensional Array


Many time we come up with the idea to create our program by using 2-D array. There are so many ways to declare the two dimensional array, some of them are here below. So without Any further delay lets start to decode this problem:

1)    

This is the most common type of declaration of the 2-D array when we come up with the default size od the 2D array:

     int array[10][5];

2)

    Dynamically allocating a two-dimensional array is a little more challenging. You may be tempted to try something like this:

int **array = new int[10][5]; // won’t work!

But it won’t work.

Now, you guys must be confused that how is this possible. Why do the compiler behaves like that. The simple answer is whenever you declare the 2d array the first thing that compiler have to know is that the size of the array i.e the coloumn size so that it can give space for the upcoming data. So for that you have to declare the coloumn size as a constant.

It must be a compile time constant.

 

So, now the question arises if not like this then how can we declare the 2d array.  There are two possible solutions here. If the rightmost array dimension is a compile-time constant, you can do this:

int (*array)[5] = new int[10][5];

The parenthesis are required here to ensure proper precedence. In C++11 or newer, this is a good place to use automatic type deduction:

Second way:

int **array = new int*[10]; // allocate an array of 10 int pointers — these are our rows

for (int count = 0; count < 10; ++count)

    array[count] = new int[5]; // these are our columns

We can then access our array like usual:

 

array[9][4] = 3; // This is the same as (array[9])[4] = 3;

 

 

 

 

 

 

 


Comments