A jagged array is an array that can have a different number of columns in each of its rows.
A dynamic array is an array that is declared in heap memory, and, unlike static arrays, we can change its size at runtime.
To create a jagged 2D dynamic array with variable column sizes, we first allocate memory for the number of rows, followed by allocating memory for columns in each row.
//Dynamically creating an array of integer pointers of size "rows"
int** ptr = new int* [ rows ];
Now, against each pointer in the array, we allocate memory for the number of columns we want.
//Dynamically allocating memory for columns in each row
for (int i = 0; i < rows; i++) {
ptr[i] = new int[cols[i]];
}
When we say we are allocating memory for rows, we are allocating memory for the “rows” number of integer pointers that would point to the arrays containing our actual data.
Next, we assign random values to the allocated memory.
time_t t ;
time ( &t ) ;
srand ( ( unsigned int ) t ) ;
for (int i = 0 ; i < rows ; i++)
{
for (int j = 0 ; j < cols[i] ; j++)
{
ptr[i][j] = rand() % 10;
}
}
Finally, we print the values of our jagged array.
for (int i = 0 ; i < 3 ; i++)
{
for (int j = 0 ; j < cols[i] ; j++)
{
std :: cout << ptr[i][j] << "\t";
}
std :: cout << std :: endl;
}
Lastly, we need to deallocate the memory that we allocated earlier.
for ( i = 0 ; i < rows ; i++ ){
delete[ ] ptr[ i ] ;
} //deleting the array that contains our actual data
delete [ ] ptr; //deleting the array that holds the pointers pointing to our actual data
RELATED TAGS
CONTRIBUTOR
View all Courses