Skip to content

Instantly share code, notes, and snippets.

@tjkhara
Created September 22, 2018 18:13
Show Gist options
  • Save tjkhara/7754fc3d6e03b6921538670e46b4f537 to your computer and use it in GitHub Desktop.
Save tjkhara/7754fc3d6e03b6921538670e46b4f537 to your computer and use it in GitHub Desktop.
Pointer pointer array with expansion.
// Example 40
// https://www.youtube.com/watch?v=c2qx13d4YG4&list=PL6xSOsbVA1eaxY06L5ZZJfDZSohwO6AKY&index=41
// C++ Example 40 - Dynamic Pointer-pointer array detailed walkthrough
#include <iostream>
#include <string>
using namespace std;
void expand(int**& arr, int& cap, int nrOfEl)
{
// Step 1 increase capacity:
cap *= 2;
// Step 2 create temp array:
int** tempArr = new int*[cap];
// Step 3 INITIALIZE TEMP ARRAY
for (int i = 0; i < cap; ++i) {
tempArr[i] = nullptr;
}
// Step 4 Copy over things from old arr
for (int j = 0; j < nrOfEl; ++j) {
// You can do this also
// tempArr[j] = arr[j]
// Or we can see from here int* ptr = new int(5)
// Replace 5 by *arr[j]
// new int(*arr[j])
tempArr[j] = new int(* arr[j]);
}
// Step 5 Deallocate arr memory
for (int k = 0; k < nrOfEl; ++k) {
delete arr[k];
}
delete[] arr;
// Step 6 Point arr to tempArr
arr = tempArr;
cout << "Array expanded. New size: " << cap << endl;
}
void add(int el, int**& arr, int& cap, int& nrOfEl)
{
if(nrOfEl >= cap)
{
expand(arr, cap, nrOfEl);
}
arr[nrOfEl++] = new int(el);
cout << el << " Element added " << "nrOfEl: " << nrOfEl << endl;
}
int main() {
int cap = 5;
int nrOfEl = 0;
int** arr = new int*[cap]; // int** arr means or int** means arr is a pointer to a pointer (the first spot of arr)
// Initialize
for (int i = 0; i < cap ; ++i) {
arr[i] = nullptr;
}
add(5, arr, cap, nrOfEl);
add(5, arr, cap, nrOfEl);
add(5, arr, cap, nrOfEl);
add(5, arr, cap, nrOfEl);
add(5, arr, cap, nrOfEl);
add(5, arr, cap, nrOfEl);
for (int k = 0; k < nrOfEl; ++k) {
cout << k << " " << arr[k] << " " << *arr[k] << endl;
}
//Delete
for (int j = 0; j < cap ; ++j) {
delete arr[j];
}
delete[] arr;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment