Skip to content

Instantly share code, notes, and snippets.

@RahulBRB
Created September 16, 2022 09:50
Show Gist options
  • Save RahulBRB/f80e91260600d8160f0a766b26e8726e to your computer and use it in GitHub Desktop.
Save RahulBRB/f80e91260600d8160f0a766b26e8726e to your computer and use it in GitHub Desktop.
Intro to Dynamic memory
#include <iostream>
// Dynamic mem: Memory that is allocated after the
// program is already compiled and running.
// Use the "new" operator to allocate memory
// in the heap rather than the stack
/* Useful when we dont know how much memory we will need.
Makes our programs more flexible, specially when
accepting user input. */
int main () {
char *pGrades = NULL;
int size;
std::cout << "How many grades to enter in?: ";
std::cin >> size;
pGrades = new char[size];
for(int i = 0; i < size; i++){
std::cout << "Enter grade #" << i + 1 << ": ";
std::cin >> pGrades[i];
}
for(int i = 0; i < size; i++){
std::cout << pGrades[i] << " ";
}
delete[] pGrades;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment