"C + + primer daily Brush Eight" Nine create a dynamic array

Source: Internet
Author: User

4.3.1. Creating dynamic Arrays


There are three important limitations to variable array types: "The length of the array is fixed", "must know its length at compile time", "the array exists only within the block statement that defines it."

Actual programs often cannot tolerate such restrictions-they need to dynamically allocate arrays at run time.

Although the array length is fixed, the dynamically allocated array does not have to know its length at compile time, and it can (and often is) determine the length of the array at run time. Unlike array variables, dynamically allocated arrays persist until the program explicitly releases it. Each program occupies a usable memory space at execution time, which is used to hold dynamically allocated objects, which are called free stores or heaps of programs.

The C language program uses a pair of standard library functions, malloc and free, to allocate storage space in a discretionary store, while the C + + language uses the new and delete expressions to achieve the same functionality.

definition of dynamic arrays

"Array variables are defined by specifying the type, array name, and number of dimensions. When allocating arrays dynamically, you only need to specify the type and array length, without naming the array object, and the new expression returns a pointer to the first element of the newly allocated array:

int *pia = new INT[10]; Array of 10uninitialized INTs

This new expression assigns an array containing 10 elements of type int and returns a pointer to the first element of the array, which initializes the pointer Pia. The new expression needs to specify the pointer type and the number of array dimensions given in square brackets, which can be any complex expression. after the array is created, new returns a pointer to the first element of the array . array objects created in free storage are not named, and programmers can access objects in the heap indirectly through their addresses. "

initializing an array of dynamically allocated

When an array is dynamically allocated, if the array element has a class type, the default constructor for that class (section 2nd 3.4) is used to initialize it, and if the array element is a built-in type, there is no initialization:

String *PSA = new STRING[10]; Array OF10 empty strings

int *pia = new INT[10]; Array of 10uninitialized INTs

These two new expressions are assigned an array of 10 objects. Where the first array is of type string, after the memory space of the saved object is allocated, the default constructor of type string is called to initialize each element of the array in sequence. The second array has elements of a built-in type and allocates memory space for storing 10 int objects, but these elements are not initialized. You can also use a pair of empty parentheses following the length of the array to initialize the value of the Set element (section

3.3.1 section):

int *pia2 = new INT[10] (); Array of 10uninitialized INTs

Parentheses require the compiler to initialize the value of the array, and in this case, set the element to 0. For a dynamically allocated array, its elements can only be initialized to the default value of the element type, not as an array variable, with an initialization list that provides different initial values for the array element.

dynamic array of const objects

If the array we create in the free store stores the const object of the built-in type, you must provide initialization for the array: Because the array elements are const objects, they cannot be assigned. The only way to implement this requirement is to initialize the value of the array:

error:uninitialized Const Array

const INT *pci_bad = new Const INT[100];

ok:value-initialized Const Array

const INT *PCI_OK = new Const int[100] ();

C + + allows you to define a const array of class types, but the class type must provide a default constructor:

Ok:array of the Empty strings

Const string *pcs = new Const STRING[100];

In this case, the array element is initialized with the default constructor of the string class. Of course, the constant elements that have been created are not allowed to be modified-so such arrays are actually of little use.

allow dynamic allocation of empty arrays

The reason that arrays are dynamically allocated is often due to the fact that the length of the array is not known at compile time. We can write the following code:

size_t n = get_size (); Get_size Returnsnumber of elements needed

int* p = new Int[n];

for (int* q = p; Q! = p + N; ++q)

/* Process the array */;

Computes the array length, and then creates and processes the array. Interestingly, what happens if Get_size returns 0? The answer is: the code still executes correctly. Although C + + does not allow the definition of an array variable of length 0, it is clear that calling new dynamically creates an array of length 0 is legal:

Char arr[0]; Error:cannot definezero-length Array

Char *CP = new Char[0]; Ok:but CP can ' tbe dereferenced

When you dynamically create an array of length 0 with new, new returns a valid non-0 pointer. The pointer is different from the other pointers returned by new and cannot be dereferenced because it does not point to any elements after all. The allowed operations include: comparison operation, so the pointer can be used in the loop, the pointer is added (minus) 0, or minus itself, 0 value.

In the example above, if Get_size returns 0, new can still be called successfully, but P does not point to any object and the array is empty. Because n is 0, the for loop actually compares P and Q, and Q is initialized with P, and both have equal values, so the FOR loop condition is not true and the loop body is not executed at once.

the release of dynamic space

The dynamically allocated memory must eventually be released, otherwise the memory will end up running out. If you no longer need to use dynamically created arrays, programmers must explicitly return the storage space they occupy to the free store of the program. The C + + language provides a pointer to the delete [] expression that releases the array space pointed to by the pointer:

Delete [] PIA;

The statement reclaims the array pointed to by the PIA and returns the corresponding memory to the free storage area. The empty square brackets between the keyword delete and the pointer are necessary: it tells the compiler that the pointer is pointing to an array in the free store, not a single object.

If an empty square bracket pair is omitted, this is an error that the compiler cannot find and will cause the program to fail at run time. In theory, the absence of empty square brackets on the collection of arrays will at least cause the runtime to free up memory space, resulting in memory leaks (leak). For some system and/or element types, there may be more serious run-time errors. Therefore, don't forget the square brackets when releasing the dynamic array.

C-style strings compared to C + + standard library type string

The following two-paragraph program reflects the difference between using a C-style string and a standard library type of C + +. Using a String type version is shorter, easier to understand, and less likely to fail:

C-style character string implementation

const char *PC = "a very long literalstring";

Const size_t len = strlen (PC + 1); Spaceto Allocate

Performance test on string Allocationand copy

for (size_t IX = 0; IX! = 1000000; ++ix) {

Char *PC2 = new Char[len + 1]; Allocatethe Space

strcpy (PC2, PC); Do the copy

if (strcmp (PC2, PC))//Use the new string

; Do nothing

delete [] PC2; Free the Memory

}

String implementation

String Str ("A Very long literalstring");

Performance test on string Allocationand copy

for (int ix = 0; IX! = 1000000; ++ix) {

string str2 = str; Do the copy,automatically

Allocated

if (str! = STR2)//Use the new string

; Do nothing

}

STR2 is

Automatically freed

These programs will be further explored in the exercises of section 4.3.1.

use of dynamic arrays

It is usually because the dimension of the array cannot be known at compile time, so it is necessary to create the array dynamically. For example, during program execution, you often use the char* pointer to point to multiple C-style strings, and you must dynamically allocate storage space in real time based on the length of each string. It is safer to use this technique than to establish a fixed-size array. If the programmer can accurately calculate the length of the array required by the runtime, there is no need to worry about the overflow problem caused by the fixed length of the factor group variable.

Suppose you have the following C-style string:

const char *noerr = "Success";

// ...

const char *err189 = "Error:afunction declaration must"

"Specify a function returntype!";

We want to copy one of these two strings to the new character array at run time, so we can calculate the dimension at run time with the following program:

const char *errortxt;

if (Errorfound)

Errortxt = err189;

Else

Errortxt = noerr;

Remember the 1 for the terminating null

int dimension = strlen (errortxt) + 1;

Char *errmsg = new Char[dimension];

Copy the text for the error into errmsg

strncpy (ErrMsg, Errortxt, dimension);

Don't forget that the standard library function strlen returns the length of the string and does not include the string terminator, which must be added 1 on the obtained string length to reserve the storage space for the Terminator when dynamically allocated.

"C + + primer daily Brush Eight" Nine create a dynamic array

Related Article

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.