Created
September 23, 2018 04:24
-
-
Save tjkhara/395eaa3a652bd6158aa0b8b9d0464f7a to your computer and use it in GitHub Desktop.
2D Dynamic Array With Pointers With Menu
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> | |
#include <iomanip> | |
#include <string> | |
using std::cout; | |
using std::cin; | |
using std::endl; | |
int main() { | |
int counter = 0; | |
// User input | |
int dimension; | |
cout << "Would you like a 2*2 or 3*3 grid?" << endl; | |
cout << "Enter 2 for 2*2 and 3 for 3*3: " << endl; | |
cin >> dimension; | |
// Create the array | |
// Start with normal pointer array | |
// int* arr = new int[dimension]; | |
// Change to an array of pointers | |
int** arr = new int*[dimension]; | |
// Allocate each pointer in the array with the number of "cols" | |
for (int i = 0; i < dimension; ++i) { | |
arr[i] = new int[dimension]; | |
} | |
// Check to see how many values need to be entered | |
cout << "Please enter " << dimension*dimension << " values: " << endl; | |
// Populate the array with values | |
for (int j = 0; j < dimension; ++j) { | |
for (int i = 0; i < dimension; ++i) { | |
cout << "Enter value " << counter++ << ": "; | |
cin >> arr[j][i]; | |
} | |
} | |
// Print the 2D array | |
for (int k = 0; k < dimension; ++k) { | |
for (int i = 0; i < dimension; ++i) { | |
if(i == (dimension-1)) | |
{ | |
cout << arr[k][i] << " " << endl; | |
} | |
else | |
{ | |
cout << arr[k][i] << " "; | |
} | |
} | |
} | |
// Deallocate memory | |
// Deallocate the news in each row | |
for (int l = 0; l < dimension; ++l) { | |
delete[] arr[l]; | |
} | |
// Deallocate the main arr | |
delete[] arr; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment