logo

Crowdly

Browser

Add to Chrome

A dynamic array is an array with dynamic storage duration. In C++, a dynamic a...

✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.

A dynamic array is an array with dynamic storage duration. In C++, a dynamic array is created on the free store using an array new expression. If T is a type and n is a non-negative integral value, expression new T[n] allocates an array of n objects of type T and returns a pointer [which has type T*] to the initial element of the array. If T is a fundamental or built-in type the array elements are left uninitialized. If T is a user-defined type, then each element of the dynamic array is initialized by running its default constructor. As an example,

int *pi {new int[10]};

will allocate memory for an array of int elements and cause pi to point to the first element. Since int is a fundamental type, the new expression doesn't initialize the dynamic array elements. The number of elements doesn’t need to be constant: the size of the array can be determined at runtime, meaning the value between brackets could be a variable rather than a literal.

To deallocate a dynamic array, use the array delete expression. Unlike the array new expression, the array delete expression doesn’t require a length:

delete [] pi;

Like the delete expression, the array delete expression returns void.

Beginner C++ programmers make the common mistake of writing the following incorrect statement to allocate a matrix of rows and columns:

int *p2i {new int[5][6]}; // error

The most efficient solution is to rely on the row-major order followed by C++ [and also by C] to conceptualize a two-dimensional array within the one-dimensional array of bytes comprising physical memory. For example, a two-dimensional array with rows and columns is conceptualized as a row-major ordered one-dimensional array of elements:

int *p2i {new int[5 * 6]};

An element located at the intersection of row and column of the two-dimensional array is accessed by mapping the offset of this two-dimensional element within the one-dimensional array pointed to by p2i:

// offset of two-dimensional element at intersection of row y and column x

int offset = y*6 + x;

Now, read the following code fragment and determine the value written to standard output stream.

int const rows{3}, columns{4};

int *p2i { new int[rows*columns]{7,10,17,12,3,14,-5,16,18,19,11,8} };

int r{1}, c{3};

std::cout << *(p2i+r*columns+c);

More questions like this

Want instant access to all verified answers on distance3.sg.digipen.edu?

Get Unlimited Answers To Exam Questions - Install Crowdly Extension Now!

Browser

Add to Chrome