Created
April 17, 2022 09:35
-
-
Save shahjugal/64f62cd715a005cb838a01b19a4815f1 to your computer and use it in GitHub Desktop.
2-D Dynamic Matrix in C++
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
/** | |
* @file DynamicMatrix.cpp | |
* @author Jugal Shah (shahjugalr@gmail.com) | |
* @brief How to allocate a 2-D(True) array dynamically. | |
* @version 0.1 | |
* @date 17/04/2022 | |
* | |
* @copyright Copyright (c) 2022 | |
* | |
*/ | |
#include <bits/stdc++.h> | |
int main(){ | |
// Pointer to a Pointer to a integer. | |
int **matrix; | |
// No of rows and columns | |
int rowCount, columnCount; | |
// Take in row and column count. | |
std::cin >> rowCount >> columnCount; | |
std::cout << std::endl; | |
// Make an array of size row count containing pointers to integer. | |
matrix = new int* [rowCount]; | |
for (int i = 0; i < rowCount; i++) | |
{ | |
// Allocate a new array of size column count for each row. | |
matrix[i] = new int [columnCount]; | |
} | |
// Store some value. | |
for (int i = 0; i < rowCount; i++) | |
{ | |
for (int j = 0; j < columnCount; j++) | |
{ | |
matrix[i][j] = i + j; | |
} | |
} | |
// Print Matrix just doing it so that can show that matrix created successfully. | |
for (int i = 0; i < rowCount; i++) | |
{ | |
for (int j = 0; j < columnCount; j++) | |
{ | |
std::cout << matrix[i][j] << " "; | |
} | |
std::cout << std::endl; | |
} | |
for (int i = 0; i < rowCount; i++) | |
{ | |
// de-Allocate an allocated array of size column count for each row. | |
delete [] matrix[i]; | |
} | |
// de-Allocates array containing pointers to those arrays which we de-allocated proviously. | |
delete [] matrix; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment