C + + dynamic memory
Understanding how dynamic within C + + works is essential to becoming a qualified C + + programmer. Memory in a C + + program is divided into two parts:
Stack: All variables declared inside the function will occupy the stack memory.
Heap: This is unused memory in the program that can be used to dynamically allocate memory while the program is running.
Many times, you cannot predict in advance how much memory is needed to store specific information in a defined variable, and the size of the required memory needs to be determined at run time.
In C + +, you can use special operators to allocate memory in the heap at run time for a variable of a given type, which returns the allocated space address. This operator is the new operator.
If you no longer need a dynamically allocated memory space, you can use the delete operator to delete the memory previously allocated by the new operator.
1#include <iostream>2 3 /*Run this program using the console Pauser or add your own getch, System ("pause") or input loop*/4 using namespacestd;5 intMainintargcChar**argv) {6 inta[2][3]={{1,2,3},{4,5,6}};7 intb[3][2],i,j;8cout <<"Array A:"<<Endl;9 for(i=0; i<=1; i++)Ten { One for(j=0; j<=2; j + +) A { -cout <<a[i][j]<<" "; -b[j][i]=A[i][j]; the } -cout <<Endl; - } -cout <<"Array B:"<<Endl; + for(i=0; i<=2; i++) - { + for(j=0; j<=1; j + +) Acout <<b[i][j]<<" "; atcout <<Endl; - } - return 0; -}
C + + dynamic memory