Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dynamic
2d array
jagged array
c++

How to use a jagged 2D dynamic array with variable column sizes

Fareeha Idrees

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.

Jagged array (An array of arrays)

Memory allocation

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 ];
Allocating memory for "rows" number of integer pointers

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.

Allocating memory for rows and columns

Assigning values

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;		
        }
}

Printing the values

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;
}

Memory deallocation

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

dynamic
2d array
jagged array
c++

CONTRIBUTOR

Fareeha Idrees
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring