Multidimension array in c++

A multidimensional array is an array of arrays. 2-dimensional arrays are the
most commonly used. They are used to store elements in a grid. Each element in
the grid can be addressed by row and column number.

let's create a grid of 5 columns and 5 rows ie 5 X 5 in size that can hold a
total number of 25 elements.

we can create this grid in the stack or heap.

let's write c++ code for both one by one.

Grid (2d array) in the stack 

#include <iostream>

using namespace std;

#define rows  5
#define cols 5


// arr: base pointer to array
// R : Number of rows 
// C : Number of columns
// value: The value to fill in the grid

void fill_grid(int* arr, int R, int C, int value) {
	// for each row in the grid
	for (int r = 0; r < R; r++) {
		// for each element in the rth row
		for (int c = 0; c < C; c++) {
			arr[r * C + c] = value;
		}
	}
}

int main()
{
	// rows and cols should be constant
	// in order to create an array in the stack
	int arr1[rows][cols];

	int *ap1 = (int*) arr1;


	// fill grid with 0's
	fill_grid(ap1, 5, 5, 0);

	// for each row in the grid
	for (int r = 0; r < rows; r++) {
		// for each element in the rth row
		for (int c = 0; c < cols; c++) {
			cout << "row = " << r << ", col = " << c;
			cout << "=> " << arr1[r][c] << endl;
		}
	}
}

Grid (2d array) in the heap

 
#include <iostream>


using namespace std;

#define rows  5
#define cols 5


// arr: base pointer to array
// R : Number of rows 
// C : Number of columns
// value: The value to fill in the grid

void fill_grid(int* arr, int R, int C, int value) {
	// for each row in the grid
	for (int r = 0; r < R; r++) {
		// for each element in the rth row
		for (int c = 0; c < C; c++) {
			arr[r * C + c] = value;
		}
	}
}

int main()
{	
	// we can dynamically create array 
    // with new keyword
	int (*arr2)[5] = new int[rows][cols];
    
	int *ap2 = (int*) arr2;

	// fill grid with 0's
	fill_grid(ap2, 5, 5, 0);

	// for each row in the grid
	for (int r = 0; r < rows; r++) {
		// for each element in the rth row
		for (int c = 0; c < cols; c++) {
			cout << "row = " << r << ", col = " << c;
			cout << "=> " << arr2[r][c] << endl;
		}
	}
}

Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *