Using new to create a dynamic array

Source: Internet
Author: User

Originally from: http://book.51cto.com/art/201211/367161.htm

Using new to create a dynamic array (1)

If a program requires only one value, a simple variable may be declared because it is easier to manage a small data object than to use new and pointers, although the impression is less impressive. In general, for large data (such as arrays, strings, and structs), you should use new, which is where new comes in. For example, suppose you want to write a program that requires an array depending on the information provided by the user at run time. If you create an array through a declaration, it allocates memory space to the program when it is compiled. Regardless of whether the program eventually uses an array, the array is there, and it takes up memory. allocating memory to an array at compile time is called static binding, which means that the groups are added to the program at compile time. when using new, however, if an array is required at run time, it is created, if not required. You can also select the length of the array while the program is running. This is called dynamic binding, which means that arrays are created when the program is run. This array is called a dynamic array. When you use a static binder, you must specify the length of the array when you write the program, and when you use dynamic linking, the program determines the length of the array at run time.

Here are two basic questions about dynamic arrays: How to create arrays using the new operator of C + + and how to use pointers to access array elements.

1. Creating a dynamic array with new

In C + +, it is easy to create dynamic arrays, as long as you tell new the array's element type and number of elements. You must enclose the type name with square brackets, which contains the number of elements. For example, to create an array that contains 10 int elements, you can do this:

The new operator returns the address of the first element. In this example, the address is assigned to the pointer psome.

when the program finishes using the memory blocks allocated by new, you should use Delete to release them. However, for arrays created with new, you should use a different format of delete to dispose of:

The square brackets tell the program that the entire array should be freed, not just the elements pointed to by the pointer. Notice the square brackets between the delete and the pointer. If you use new without square brackets, you should not have square brackets when you use Delete. If you use new with square brackets, you should also use Delete with square brackets. An earlier version of C + + did not recognize the square bracket notation. However, for the Ansi/iso standard, the result of a mismatch between the new and delete formats is indeterminate, which means that the programmer cannot rely on a particular behavior.

In summary, the following rules should be followed when using new and delete.

Do not use Delete to release memory that is not allocated by new.

Do not use Delete to release the same block of memory two times.

If you use new [] to allocate memory for an array, you should use delete [] to release it.

If you use new [] to allocate memory for an entity, you should use Delete (no square brackets) to release it.

It is safe to apply a delete to a null pointer.

Now let's go back to discussing dynamic arrays. Psome is a pointer to an int (the first element of the array). Your responsibility is to track the number of elements in the memory block. That is, because the compiler cannot trace the fact that Psome is a 1th of 10 integers, you must have the program keep track of the number of elements when you write the program.

In fact, the program does track the amount of memory allocated so that it can be properly freed later when the delete [] operator is used. However, this information is not common, for example, you cannot use the sizeof operator to determine the number of bytes that a dynamically allocated array contains.

The common format for allocating memory for arrays is as follows:

Using the new operator ensures that a block of memory is sufficient to store num_elements elements of type type_name, and pointer_name points to the 1th element. As you'll see below, you can use Pointer_name in a way that uses array names.

2. Working with dynamic arrays

After creating a dynamic array, how do you use it? First, consider the problem conceptually. The following statement creates pointer Psome, which points to the 1th element in a memory block that contains 10 int values:

It can be thought of as a finger pointing to the element. Assuming an int occupies 4 bytes, the finger moves 4 bytes in the correct direction, and the finger points to the 2nd element. There are a total of 10 elements, which is the movement range of the fingers. Therefore, the new statement provides all the information needed to identify each element in a memory block.

Now consider this problem from a practical point of view. How do I access the elements? The first element is not a problem. Because Psome points to the 1th element of the array, *psome is the value of the 1th element. This way, there are 9 more elements. If you haven't used the C language, the simplest of these methods might surprise you: just use the pointer as an array name. That is, for the 1th element, you can use psome[0] instead of *psome; for the 2nd element, you can use psome[1], and so on. Thus, it is very easy to use pointers to access dynamic arrays, although it is not yet known why this approach works. The reason you can do this is that both C and C + + use pointers to handle arrays. The basic equivalence of arrays and pointers is one of the advantages of C and C + + (this is sometimes a problem, but this is another matter). This equivalence will be described in more detail later.

First, listing 4.18 shows how to use new to create a dynamic array and use array notation to access the element; It also points to the fundamental difference between a pointer and a true array name.

Using new to create a dynamic array (2)

Program Listing 4.18 Arraynew.cpp

The following is the output of the program:

From this, Arraynew.cpp uses the pointer p3 as the array name, P3[0] as the 1th element, and so on. The following line of code indicates the fundamental difference between the array name and the pointer:

The value of the array name cannot be modified. But the pointer is a variable, so you can modify its value. Note the effect of adding P3 to 1. Expression P3[0] Now refers to the 2nd value of the array. Therefore, adding a P3 of 1 causes it to point to the 2nd element instead of the 1th. After you subtract 1, the pointer points to the original value so that the program can provide the correct address for delete[.

Adjacent int addresses usually differ by 2 bytes or 4 bytes, and after P3 plus 1, it will point to the address of the next element, indicating that pointer arithmetic has some special place. This is indeed the case.

Using new to create a dynamic array

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.