Professional Documents
Culture Documents
2.03 Dynamic Allocation of Arrays
2.03 Dynamic Allocation of Arrays
Dynamic allocation
of arrays
• In the last topic, we allocated instances of a type: • How do we allocate and deallocate arrays?
int main() { int main() {
int *p_int{ new int{91} }; int *array{ new int[100]{} };
std::cout << p_int << std::endl; std::cout << array << std::endl;
std::cout << *p_int << std::endl; std::cout << array[19] << std::endl;
*p_int = 7; array[19] = 2;
std::cout << ((*p_int + 1)*(*p_int - 1)) << std::endl; std::cout << (7*array[19]*(array[19] + 1)) << std::endl;
1
2020-10-01
• Initialization is potentially expensive, so you can opt out: • Naming conventions are useful:
int main() { – Arrays should be plural or contain a word such as array or table
std::size_t capacity{100};
double *array{ new double[capacity] }; control_points control_pt_array
std::cout << array[15] << std::endl; Output:
-1.25e-302 – Another option for dynamically allocated arrays is to prefix the
for ( std::size_t k{0}; k < capacity; ++k ) {
0.997494 name with an a_
array[k] = std::sin( 0.1*k );
} 0.75 a_control_point
delete[] array;
array = nullptr;
return 0;
}
• Suppose you request more memory than the operating system can • Alternatively, it is possible to force new to simply return nullptr if
allocate—for example, 1 GiB memory is not available:
– Remember, the memory must be contiguous int *a_data{new(nothrow) int[capacity]};
2
2020-10-01
Summary References
Colophon Disclaimer
These slides were prepared using the Georgia typeface. Mathematical These slides are provided for the ECE 150 Fundamentals of
equations use Times New Roman, and source code is presented using Programming course taught at the University of Waterloo. The
Consolas. material in it reflects the authors’ best judgment in light of the
information available to them at the time of preparation. Any reliance
The photographs of lilacs in bloom appearing on the title slide and on these course slides by any party for any other purpose are the
accenting the top of each other slide were taken at the Royal Botanical responsibility of such parties. The authors accept no responsibility for
Gardens on May 27, 2018 by Douglas Wilhelm Harder. Please see damages, if any, suffered by any party as a result of decisions made or
actions based on these course slides for any other purpose than that for
https://www.rbg.ca/ which it was intended.
for more information.