What is the method for initializing and assigning values to dynamic arrays in C++?
In C++, dynamic arrays can be initialized and assigned values in several ways:
- Allocate memory dynamically using the new operator and the size of the array, then assign values one by one using a loop or index.
int size = 5;
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
- Allocate memory and initialize array elements dynamically using the new operator and initializer list.
int* arr = new int[5]{1, 2, 3, 4, 5};
- Use the vector container class to create a dynamic array and assign values using an initialization list or the push_back() function.
#include <vector>
std::vector<int> arr = {1, 2, 3, 4, 5};
// 或者
std::vector<int> arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
Whether utilizing raw pointers or container classes, it is essential to manually release memory or let objects go out of scope to free memory automatically. For instance, using the delete operator to release memory of a raw pointer:
delete[] arr;