Last active
September 8, 2021 05:21
-
-
Save rugbyprof/1677341 to your computer and use it in GitHub Desktop.
Dynamic 2D array
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
#include <iostream> | |
using namespace std; | |
int main() { | |
int **Matrix; //Declare a pointer to pointer (integer in this case). | |
int maxRows = 5; //Size in rows of your array. | |
int maxCols = 5; //Size in cols of your array (does not have to == rows, could be a staggered array). | |
Matrix = new int *[maxRows]; //Point table to an array of size maxRows holding null pointers right now. | |
/* | |
Line 10 creates this: | |
Matrix=>[0]=> UNDEFINED | |
[1]=> UNDEFINED | |
[2]=> UNDEFINED | |
[3]=> UNDEFINED | |
[4]=> UNDEFINED | |
*/ | |
//Loop row times pointing each array location to a newly allocated | |
//array of (int's in this case) of whatever size (size maxCols in this case). | |
for (int row = 0; row < maxRows; row++) { | |
Matrix[row] = new int[maxCols]; | |
} | |
/* | |
Lines 26-28 creates this: | |
0 1 2 3 4 | |
Matrix=>[0]=> [ ][ ][ ][ ][ ] | |
[1]=> [ ][ ][ ][ ][ ] | |
[2]=> [ ][ ][ ][ ][ ] | |
[3]=> [ ][ ][ ][ ][ ] | |
[4]=> [ ][ ][ ][ ][ ] | |
Which is essentially: | |
0 1 2 3 4 | |
0 [ ][ ][ ][ ][ ] | |
1 [ ][ ][ ][ ][ ] | |
2 [ ][ ][ ][ ][ ] | |
3 [ ][ ][ ][ ][ ] | |
4 [ ][ ][ ][ ][ ] | |
Accessed like: Matrix[2][3] = 10; | |
*/ | |
// load array with random values | |
for (int i = 0; i < maxRows; i++) { | |
for (int j = 0; j < maxRows; j++) { | |
Matrix[i][j] = rand() % 100; | |
} | |
} | |
// print array | |
for (int i = 0; i < maxRows; i++) { | |
for (int j = 0; j < maxRows; j++) { | |
cout << Matrix[i][j] << " "; | |
} | |
cout << endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment