What is the method for initializing a dynamic array in C++?

A common way to initialize dynamic arrays in C++ is by using the “new” keyword.

int size = 5; // 数组大小
int* arr = new int[size]; // 动态分配大小为size的整型数组

// 初始化数组元素
for (int i = 0; i < size; i++) {
    arr[i] = i; // 将数组元素赋值为索引值
}

// 使用数组

// 释放数组内存
delete[] arr;

In the example above, memory space for an integer array with a size of “size” was dynamically allocated using the “new” keyword. Next, a for loop was used to initialize the array by assigning each element its corresponding index value. Finally, the memory space of the array was released using the “delete[]” keyword to prevent memory leaks.

bannerAds