In Programming many times we have to store and work with the data. But choosing the right way of storing is important.
Array is one of the most simple and effective way of storing list of data.Now we have to multiple array of data. Ohh! that sounds easy we can use 2 Dimensional Array.
I agree 2 Dimensional array is suitable but I have arrays of variable lengths. So simply creating 2-D Array will not be efficient because I have to specify the column size as the highest of my arrays. So there will be lot of unused space.
The good solution can be Dynamic 2D Array with variable columns. Also Array of vectors can also be used. But we are not discussing about STL.

Algorithm:
- Create a ptr to ptr to ptr with the name of your 2D Array to hold the Array of Pointers.
- Now create an Array of pointers depending on the no of rows and store the base address on the ptr to ptr.
- For every Row allocate the required memory and store the address in the array of pointers.
- You own the 2D Dynamic Array with Dynamic Rows and Columns.
Implementation:
I have done it in c++. But your choice may vary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
int main() | |
{ | |
//No of Rows and Columns | |
int row = 5, col[] = {4, 2, 6, 5, 1}; | |
//Create a ptr to ptr | |
int **myList; | |
//Store Array of ptr in myList | |
myList = new int*[row]; | |
//now Allocate memmory for Dynamic colums and store in Array of ptr(Row) | |
myList[0] = new int[col[0]]; | |
myList[1] = new int[col[1]]; | |
myList[2] = new int[col[2]]; | |
myList[3] = new int[col[3]]; | |
myList[4] = new int[col[4]]; | |
/* You have 2D Dynamic Array with Dynamic Rows and Columns. | |
you can also operate during runtime without any problem.*/ | |
for(int i = 0; i < row; i++) | |
{ | |
for(int j = 0; j < col[i]; j++) | |
{ | |
cout<<myList[i][j]<<' '; | |
} | |
cout<<endl; | |
delete[] myList[i]; | |
} | |
delete[] myList; | |
return 0; | |
} |
You can play with this list at your own choice..
Comments
Post a Comment