Computer Fundamentals |
|---|
| What is computer? |
| Software |
| Hardware |
| Operating System |
Programming Language |
| Java |
| C# |
| Python |
| Visual Basic |
| Jscript.NET |
Web Development
|
| HTML |
| ASP |
| PHP |
| JavaScript |
| VBScript |
.NET |
| .NET Micrsoft |
| ASP.NET |
| .NET Mobile |
Forum |
| VB/VB.NET |
| ASP/ASP.NET |
| VBScript |
| JavaScript |
| Topic: C++-Language Dynamic Memory Allocation Until now, in our programs, we have only had as much memory as we have requested in declarations of variables, arrays and other objects that we included, having the size of all of them fixed before the execution of the program. But, what if we need a variable amount of memory that can only be determined during the program execution (runtime), for example, in case that we need an user input to determine the necessary amount of space? The answer is dynamic memory, for which C++ integrates the
operators new and delete. pointer = new typeor pointer = new type [elements]The first expression is used to assign memory to contain one single element of type. The second one is used to assign a block (an array) of elements of type. For example: int * bobby;in this case, the operating system has assigned space for 5 elements of type int in a heap and it has returned a pointer to its beginning that has been assigned to bobby. Therefore, now, bobby points to a valid block of memory with space for 5 int elements. ![]() You could ask what is the difference between declaring a normal array and assigning memory to a pointer as we have just done. The most important one is that the size of an array must be a constant value, which limits its size to what we decide at the moment of designing the program before its execution, whereas the dynamic memory allocation allows assigning memory during the execution of the program using any variable, constant or combination of both as size. The dynamic memory is generally managed by the operating system, and in multitask interfaces it can be shared between several applications, so there is a possibility that the memory exhausts. If this happens and the operating system cannot assign the memory that we request with the operator new, a null pointer will be returned. For that reason it is recommended to always check to see if the returned pointer is null after a call to new. int * bobby; Operator delete. delete pointer;or delete [] pointer; // rememb-o-matic #include <iostream.h> #include <stdlib.h> int main () { char input [100]; int i,n; long * l; cout << "How many numbers do you want to type in? "; cin.getline (input,100); i=atoi (input); l= new long[i]; if (l == NULL) exit (1); for (n=0; n<i; n++) { cout << "Enter number: "; cin.getline (input,100); l[n]=atol (input); } cout << "You have entered: "; for (n=0; n<i; n++) cout << l[n] << ", "; delete[] l; return 0; }
|
|