/* This program demonstrates * 1. Dynamic Memory * 2. Dynamic Arrays * * Dynamic Arrays: * So far, we have been declaring arrays in stack space. These arrays need to have * their size decided BEFORE COMPILING. That is why we had to use integer literals * or constant integers for size while declaring the arrays. We decided this size * hoping that it would be "large enough" to hold all the data the user is going * to put in. * * Also, we cannot create arrays in one function (that is not main) and use it in * other functions. * * Dynamic memory solves both of these problems. * 1. Declaration * We declare dynamic memory using the keyword "new". * When we declare a variable/array dynamically, the variable/array is created in * a completely different area of memory called the heap. This happens at RUNTIME. * So, we can use a variable to specify the size of the array. * 2. Access * We can access variables/arrays created in heap memory ONLY through a pointer. * 3. Deleting * Since we create this memory in runtime, this is not automatically deleted when * we return from a function. This is useful because we can create arrays in a * function and return it. However, we should take care to delete the memory we * created before we exit the program. To delete memory we created, we use the * keyword "delete". Please note that deleting doesn't have to be done in the * same function that created the array. * */ #include using namespace std; /* When we want to return an array from a function, the return type has to be * a pointer of the type of the array that we're returning. */ int* readArray(int count); int* readDynArray(int count); int* insert(int *arr, int size, int val, int pos); int main() { /* If we create a stack-space array in a function, it would be destroyed * when we return from the function. So, if we try to access that array from * main, it would either print junk values or crash with a segmentation fault */ int *intArr = nullptr; int size; cout<<"Enter the number of elements: "; cin>>size; intArr = readArray(size); // The previous line will retrun an invalid reference, which would crash if we used it /* Instead of using the readArray function that creates an in-stack array * and returns an array that is subsequently destroyed, we can create a dynamic * array in the function, retrun it, use it in main, and delete it when it * is no longer required. */ intArr = readDynArray(size); cout<<"\nPrinting from main: \n"; for(int i=0; i>num; cout<<"Enter the position: "; cin>>pos; // Call the insert function and then store the returned array in the same pointer intArr = insert(intArr,size,num,pos); size++; // we have 1 more element cout<<"\nArray after insert:\n"; for(int i=0; i>array[i]; cout<<"Printing from the function:\n"; for(int i=0; i>array[i]; cout<<"Printing from the function:\n"; for(int i=0; i