How to create and use dynamic arrays in C++

In C++, dynamic arrays can be created and used using pointers and the keyword ‘new’. Here is a simple example:

#include <iostream>

int main() {
  int size;

  // 输入数组大小
  std::cout << "请输入数组大小:";
  std::cin >> size;

  // 建立动态数组
  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 example, firstly, an array containing size number of int elements is dynamically allocated using the new keyword. Then, the input array elements are traversed through a loop, followed by the output array elements. Finally, the memory space occupied by the dynamic array is released using delete[].

It is important to note that when using dynamic arrays, it is crucial to ensure that memory is released promptly when no longer needed to prevent memory leaks.

bannerAds