How to define dynamic arrays in C++?

In C++, dynamic arrays can be implemented by allocating memory using the new keyword.

Here is an example code defining a dynamic array:

#include <iostream>

int main() {
    int size;
    std::cout << "请输入数组的大小:";
    std::cin >> size;

    // 使用new关键字动态分配内存
    int* arr = new int[size];

    std::cout << "请输入数组元素的值:";
    for (int i = 0; i < size; i++) {
        std::cin >> arr[i];
    }

    std::cout << "数组元素的值为:";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    // 释放内存
    delete[] arr;

    return 0;
}

In the above code, a dynamically allocated integer array of size “size” is created using the new keyword. Then, a loop is used to store user input values into the array, and another loop is used to print out the elements of the array. Finally, it is necessary to use the delete[] operator to release the allocated memory in order to prevent memory leaks.

bannerAds