What is the method to assign values to a dynamic array in C++?
In C++, dynamic arrays can be created using the new operator and assigned values using the assignment operator =. Here is a common method:
- Create a dynamic array using the new operator and assign it to a pointer variable.
int size = 5; // 数组大小
int* arr = new int[size]; // 创建动态数组并分配内存
- Traverse the array using a looping structure and assign values to its elements using the assignment operator =.
for (int i = 0; i < size; i++) {
arr[i] = i + 1; // 给数组元素赋值
}
Caution: after using dynamic arrays, remember to use the delete operator to release memory.
delete[] arr; // 释放动态数组内存