Skip to content

Instantly share code, notes, and snippets.

@Loki-Astari
Created January 20, 2021 06:28
Show Gist options
  • Select an option

  • Save Loki-Astari/2189f23d331a4237cd80dd4df78e8c69 to your computer and use it in GitHub Desktop.

Select an option

Save Loki-Astari/2189f23d331a4237cd80dd4df78e8c69 to your computer and use it in GitHub Desktop.
Examples of allocation
// Version 1
// Your version
// Two layers of indirection.
std::string** myArray = new string*[size]; // call to new must be matched with delete.
for (int loop; loop < size; ++loop) {
myArray[loop] = new string; // call to new must be matched with delete.
std::getline(std::cin, myArray[loop][0], '/');
std::getline(std::cin, myArray[loop][1]);
}
// Does not take into account exceptions.
// Version 2
// Single layer of indirection
using Row = std::string[2];
Row* myArray = new Row[size]; // call to new must be matched with delete.
for (int loop; loop < size; ++loop) {
// No need for a new here. You have allocated size
// objects that contain 2 strings.
std::getline(std::cin, myArray[loop][0], '/');
std::getline(std::cin, myArray[loop][1]);
}
// Does not take into account exceptions.
// Version 3
// Single layer of indirection
using Row = std::string[2];
using Array = std::vector<Row>;
Array myArray{Row{}, size); // No dynamic allocation
for (int loop; loop < size; ++loop) {
// No need for a new here. You have allocated size
// objects that contain 2 strings.
std::getline(std::cin, myArray[loop][0], '/');
std::getline(std::cin, myArray[loop][1]);
}
// Exceptions handeled gracefully.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment