The two main differences between static and dynamic memory allocation are:
1. A static object is a variable with a name. We can operate on it directly. A dynamic object is a variable without a name. We operate it indirectly through a pointer.
2. the compiler automatically allocates and releases static objects. ProgramPersonnel need to understand this, but do not need to do anything. On the contrary, the distribution and release of dynamic objects must be managed by the programmer explicitly, which is relatively error-prone and completed by the new and delete expressions.
The Dynamic Distribution of objects can be completed through one of the two versions of the new expression. The first version is used to allocate a single object of a specific type.
For example: int * pint = new int (1024 );
Returns the address of the object in the memory. Next, this address is used to initialize the pointer object pint.
The second version of the new expression, used to allocate arrays of specific types and digits.
For example: int * Pia = new int [4];
An array containing four integer elements is allocated. Unfortunately, we cannot explicitly specify an initial value for each element of the dynamically allocated array.
When Dynamic Allocation of objects or arrays of objects and places is used up, the memory must be explicitly released. We can do this by using the delete expression in one of the two versions,
For example, deleting a single object
Delete pint;
The delete expression in the array form is:
Delete [] PIA;
If you forget to delete the dynamically allocated memory, the program will end with a memory leak (Memory Leak. From: http://programmingart.blog.51cto.com/213782/43497
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service