arrays, pointers, and strings: Dynamic memory allocation and deallocation

Source: Internet
Author: User

Dynamic memory allocation is most commonly used to allocate an array of some type. We can use arrays to handle a lot of data, but in many cases we don't know how many elements this array will have, so it's a good idea to think about how much of an array to define when you define an array. For example, we have to analyze the number of inputs and get all the positive numbers to be stored in an array for his use, and how large the array of positive numbers should be defined. If it's large, it can be a waste of memory, and if it's small, the array may be out of bounds. In this case, the ideal is to determine how many positive numbers in the total number of the definition of how much of the array, neither waste memory nor the array out of bounds, which requires the use of dynamic memory allocation.

Dynamic memory allocation refers to the dynamic allocation of the right amount of memory according to the actual situation in the process of operation, and then release after use. The memory units that are requested and freed during dynamic memory allocation are called heap objects. The process of application and release is generally called establishment and deletion.

A. C + + dynamic memory allocation operator: New and delete

The new operator in C + + is used to dynamically allocate memory, or it can be called a dynamic create heap object. The syntax for dynamically allocating memory using the new operator is:

New type name (initial value list);

Use this statement to request the allocation of a memory space that holds data of the type represented by type name and is initialized with the values listed in the initial value list. The statement returns a pointer to the type represented by the type name, or null if the allocation fails.

When we create a normal variable dynamically, the initialization is to assign a value to it. For example:

int *p;
p = new int (10);

The above statement dynamically allocates the memory space used to hold an integer data, while the initial value of 10 is deposited into the memory space, that is, the shaping data that P points to is 10, and finally assigns the first address of the allocated memory to P.

If we build the object of a class dynamically, then the appropriate constructor for that class is called based on the list of initial values.

The delete operator is used to remove the heap object that was created dynamically with new, freeing new dynamically allocated heap memory. The syntax for using the delete operator is:

Delete pointer name;

If a normal variable is removed, the dynamically allocated memory is released directly. If the object is deleted, the destructor of the object is invoked. Notice here that the dynamically allocated memory with new is only released once with delete, and if the second time it is released, an error occurs.

Examples of dynamically created objects:

        #include <iostream>        using namespace std;             class cstudent        {      &NBSP;PUBL IC:                  cstudent ()        & nbsp;      {cout<< "Default constructor called." <<endl; }         //parameterless constructors               & nbsp  cstudent (int nage)       {m_nage = nage; cout<< "constructor called." <<endl; }  //With parameter constructors                  ~cstudent ()    &nbs p;         {cout<< "destructor called." <<endl; }                              //destructor                  int getage ()             { return m_nage; }      //inline function, back m_nage        private:         &N Bsp        int m_nage;       //Private data        };        int main ()        {                Cstudent *ptr = new cstudent;        //Dynamic Creation object, no list of initial values, so call parameterless constructor   & nbsp             Delete ptr;                                                //Delete objects, automatically invoke destructors                 ptr = new Cstudent (;            )         //Dynamically create object, give initial value, so call constructor with parameter                 Delete ptr;                                               //delete objects, automatically invoke destructors                 return 0;       &NBSP;}

The results of the program run are:

Default constructor called.
destructor called.
Constructor called.
destructor called.

You can also create heap objects of array types with operator new, and the syntax for dynamically creating one-dimensional arrays is:

New type name [subscript expression];

The subscript expression above indicates the number of elements in the array. If the dynamic allocation of memory succeeds, a pointer to the first address of the allocated memory is returned, or null if the allocation fails. Note here that you cannot specify the initial value of an array element when dynamically allocating memory on an arrays.

An array that is created dynamically with new can also be deleted with delete, but the pointer name should be added "[]". The syntactic form of the delete array is:


Delete [] pointer name;


A simple example of creating an array of objects dynamically:


        #include <iostream>        using namespace std;             class cstudent        {      &NBSP;PUBL IC:                  cstudent ()             &NB Sp {cout<< "Default constructor called." <<endl; {         //parameterless constructor                  cstudent (int nage)      {m_nage = nage cout<< "constructor called." <<endl;  ///with parameter constructors                  ~cstudent ()             {cout<< "destructor called." <<endl; }                              /destructor                  int getage ()            {return m_nage}      //inline function, back to m_nage       &NBSP;PRI Vate:                  int m_nage;        //private data        };        int main ()        {                Cstudent *ptr = new Cstudent[2];      //dynamically create object arrays, invoke parameterless constructors for each object element                 delete []ptr;                        //Delete object array, automatically invoke destructor for each object                 return 0;       &NBSP;}

The results of the program run are:


Default constructor called.
Default constructor called.
destructor called.
destructor called.


The syntax for creating a multidimensional array dynamically with new is:


New type name t[subscript expression 1][subscript expression 2] ...;


The subscript expression 1 above can be any expression that results in a positive integer, while the other subscript expression must be a constant expression with a positive integer result. This statement returns a pointer to the first address of the allocated memory if the execution succeeds, but the pointer is not a pointer to a type T, but a pointer to an array of type T.


For example: int *p = new Int[2][3]; it's wrong, because here new returns a pointer to a one-dimensional int array with 3 elements, and p is a pointer to int data. Here you may have two questions: 1. Is not a two-dimensional array assigned, how to return a pointer to a one-dimensional array. 2. How to declare a pointer to an array.


Answer: 1. We can think of multidimensional arrays as one-dimensional arrays of other dimensional data except the first dimension. The number of elements in this one-dimensional array is the value of the first subscript expression, such as int[2][3], which can be viewed as a one-dimensional array of 2 elements, each containing 3 integers. New creates a multidimensional array that returns a pointer to the first element (also an array) of a one-dimensional array, and for new int[2][3] The first element is actually the first row of a two-dimensional array, and the first element of the new int[2][3][4 is actually a 3x4 two-dimensional array.


2. Declares a pointer to an array in the form of:


Type name (* pointer name) [Subscript expression 1][subscript expression 2] ...;


The correct notation for dynamically creating the above two-dimensional array is as follows:


int (*p) [3]; Declares a pointer to an array
p = new Int[2][3]; To create a two-dimensional array dynamically


You can access the elements of this two-dimensional array in the following form:


for (int i=0; i<2; i++)
{
for (int j=0; j<3; j + +)
{
* (* (p+i) +j) = 0; To access an array element through a pointer
}
}


Two. Inherited from C language dynamic memory allocation and release functions


In addition to using the new and delete operators for dynamic memory management, the C + + language inherits the dynamic memory management functions of the C language.


1. Dynamic Memory allocation function


void *malloc (size); The parameter size is the number of bytes to allocate. Returns a pointer of type void when a function executes successfully, or null when execution fails.


2. Dynamic Memory Release function


void free (void *memblock); parameter memblock is a pointer to the memory to be freed. This function does not have a return value.



Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.