You are on page 1of 4

DEPARTMENT OF COMPUTER SCIENCE

( Rachna College of Engineering and Technology Gujranwala )

DATA STRUCTURES AND ALGORITHMS

Name: Registration No:

LAB 02

DYNAMIC ARRAYS AND JAGGED ARRAYS


Dynamic Memory Allocation:

Memory allocated at time of execution is called as dynamic memory. It is allocated on heap. On


heap memory is allocated or deallocated without any order/randomly.

POINTERS play an important role in Dynamic Memory Allocation and allocated memory can
only be accessed by POINTERS.

MULTIDIMENSIONAL ARRAYS

Multidimensional Arrays can be defined as array of arrays i.e. a combination of multiple


arrays.e.g.

int Arr2D[3][5]

int Arr3D[3][3][4]

How to visualize Multi dimensional Arrays??

int Arr1D [5] = {1,2,3,4,5}

int Arr2D [3][5] ={


{1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}
}

int Arr3D [2][3][3] = {


{ {1,2,3}, {1,2,3}, {1,2,3} },
{ {4,5,6}, {4,5,6}, {4,5,6} }
}

Processing the Multidimensional Arrays

C++ CODE oF 2D ARRAY

//*********** 2D Arrays ***********//

#define R 5
#define C 4
// dynamically create array of pointers of size M
int** A2D = new int*[R];

// dynamically allocate memory of size N for each row


for (int i = 0; i < R; i++)
A2D[i] = new int[C];

// assign values to allocated memory


for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
A2D[i][j] = rand() % 100;

cout<<"\nPrinting 2D Array Elements"<<"\n\n";


// print the 2D array
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
cout << A2D[i][j] << " ";

std::cout << std::endl;


}

// deallocate memory using delete[] operator


for (int i = 0; i < R; i++)
delete[] A2D[i];

delete[] A2D;
a = Pointer to 1st 2D Array = 1000 a+1 = Pointer to 2nd 2D Array = 1016

*(a+1) = Pointer to 1st 1D Array of 2nd 2D Array

*(*(a+1)) = Pointer to 1st Element 1st 1D Array of 2nd 2D Array

**(*(a+1)) =5= a[1][0][0]

JAGGED ARRAYS

Jagged array is a array of arrays such that member arrays can be of different sizes i.e. they
have different number of columns in each of its row.

LAB TASKS

1- Write a C++ Program to Allocate and Display a 1D Array, 2D Array, 3D Array using
Dynamic Memory Allocation
2- Write a C++ Program to implement a Jagged Array

You might also like