Created
September 23, 2018 03:58
-
-
Save tjkhara/b10448a62284054fa48fbe201c78654b to your computer and use it in GitHub Desktop.
Simple 2D array with pointers
This file contains hidden or 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> | |
#include <iomanip> | |
#include <string> | |
using std::cout; | |
using std::cin; | |
using std::endl; | |
int main() { | |
// We want an array of pointers | |
// Start with simple dynamic array | |
// int* arr = new int[5]; | |
// This is an array of int | |
// We want array of pointers | |
int** arr = new int*[5]; | |
// This is an array of pointers | |
// int** arr means arr is a pointer to a pointer | |
// arr is the first element of the array and it points to a pointer | |
// Now we want to assign arrays to each of the cells in the array | |
// Let's start with the first one | |
// arr[0] = new int[10]; | |
// In arr[0] we have a pointer. That pointer has been initialized to | |
// an array or 10 elements. | |
// We can repeat the same process in a loop to initialize all "rows" | |
/*// Moved below to inside the loop | |
for (int i = 0; i < 5; ++i) { | |
arr[i] = new int[10]; // Initialize all pointers to a new array of 10 elements | |
}*/ | |
// Now let's point these pointers to some values | |
for (int i = 0; i < 5; ++i) { | |
arr[i] = new int[10]; // Allocate memory (step on line 35) | |
for (int j = 0; j < 10; ++j) { | |
arr[i][j] = 10; // Initialize with value | |
} | |
} | |
// Print out these values to see | |
for (int k = 0; k < 5; ++k) { | |
for (int i = 0; i < 10; ++i) { | |
if(i == 9) | |
{ | |
cout << arr[k][i] << endl; | |
} | |
else | |
{ | |
cout << arr[k][i] << " "; | |
} | |
} | |
} | |
// We have to deallocate this memory as well | |
// Look for all the new | |
// deallocate all the arrays in each cell (the "rows") | |
for (int l = 0; l < 5; ++l) { | |
delete[] arr[l]; | |
} | |
// deallocate the array of pointers | |
delete[] arr; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment